PHP Global namespace aliases

痞子三分冷 提交于 2020-01-11 12:28:29

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/19890310/php-global-namespace-aliases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!