Search code examples
phpnamespacesglobal-namespacenamespace-organisation

PHP Global namespace aliases


Here is the scenario.

I am implementing namespaces into my projects.

I have my own custom bridge library that calls other libraries like Zend to do the heavy lifting.

I have no problem using fully qualified namespaces in my custom bridge library but would like to keep the code as terse as possible in my controllers, models and view.

Here is an example of some aliasses i would like to use:

use BridgeLibName\Stdlib\Arrays as arr;
use BridgeLibName\Stdlib\Objects as obj;
use BridgeLibName\Stdlib\Strings as str;
use BridgeLibName\Stdlib\Numbers as num;
use BridgeLibName\Stdlib\File as file;
etc.........

Example usage:

$file = new file('path/to/file.txt');
$file->create();

or

$obj = arr::toObject(['key1'=>'value1']);

is it possible in any way to create an alias or constant that can be globally accessible and not discarded at the end of each file?

Some kind of bootstrap file that can make these aliases stick.


Solution

  • As I was writing the question i thought of a solution.

    You can fake it by creating classes that extend the namespaced classes.

    example:

    class arr extends BridgeLibName\Stdlib\Arrays{
    
    }
    

    One important thing to remember:

    If you are going to extend the classes the namespaced class will have to be loaded.

    This could have performance implications if used too much since aliases and namespaces are only loaded as needed.

    Since I am only using it to bridge to other classes there is very little logic inside my bridge files.

    These bridge files in turn uses aliases and namespaces correctly thus loading the real files as needed.

    I you are not careful with the implementation you can load a lot of unnecessary stuff and cause your app to become slow and bloated.


    A nice thing I noticed is that good IDEs like netbeans also seems to be able to do auto completion with this method.


    If there is a better way to do this please let me know.


    Just thought of an amendment to this method to fix the problem with unnecessary class instantiation.

    The core library can work with the normal psr-0 loader.

    To have the aliases autoload I created an aditional dir named includes next to my namespaced class.

    in composer you describe it like so:

    "autoload": {
        "psr-0": {
            "BridgeLibName\\": "."
        },
        "classmap": ["include/"]
    }
    

    Now your libraries will load as expected from the correct namespace and your alias classes will autoload as needed.

    Classes put into the include dir can now extend the namespaced classes ( as shown above ) and will no longer be loaded prior to being used.

    Now you have global aliases without having to sacrifice performance by loading unused classes.