PHP Global namespace aliases

给你一囗甜甜゛ 提交于 2019-12-02 05:20:49

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.

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