开发者

Relocating and renaming classes using namespaces

I have a number of older classes that I'd like to transition into a PSR-0 style directory. I'd like a sanity check on my process.

  1. Rename and relocate the existing FooPerson.class.php file to Foo/Person.php.
  2. Create namespace Foo in Person.php, and update all class references to be na开发者_运维百科mespace-compatible as appropriate.
  3. For compatibility with old code, create a new FooPerson.class.php with this content:

    <?php
    
    require 'autoload.php'; // our psr-0 autoloader
    class_alias( '\Foo\Person', 'FooPerson' );
    

My hope is that this will enable transparent instantiation using either new FooPerson or new \Foo\Person. Initial testing seems to support this. Are there pitfalls I should be aware of?


I don't see any pitfalls. However, I suggest to use another approach, because this one may let you miss the one or another old classname. Either you remove FooPerson completely, in which case you will realize the hard way, where you forgot to change the classname, or create a dummy class, that helps you keep track with a message when someone tries to use it.

// File 'FooPerson.php'

trigger_error("Class 'FooPerson'", E_USER_DEPRECATED);
class FooPerson extends \Foo\Person {}

Because the class-to-filename-mapping is valid according the psr-0 standard, this file gets loaded by your autoloader too. In the case it is loaded by the autoloader, a E_USER_DEPRECATED is emitted and you can fix it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜