ZF2: autoloading libraries without namespaces

◇◆丶佛笑我妖孽 提交于 2019-12-01 04:55:24

问题


Previously I have only been using third party libraries that use namespaces together with Zend Framework 2. Now I need to use a library that does not use namespaces, and I cannot seem to make it work. I installed it via Composer, and it is installed fine into the vendor directory. I am trying to use it as follows:

$obj = new \SEOstats();

The result is a fatal error indicating that the class could not be found. I have tried to manually configure the StandardAutoloader, but so far without any luck. I thought that the autoloading would be done for me automatically when installing through Composer, but I guess that is not the case without namespaces? I haven't seen any reference to the library in the autoload files that Composer generated. I guess I have to do it manually - but how?

Thanks in advance.


回答1:


You can use the files and classmap keys.

As an example consider this composer.json:

{
    "require": {
        "vendor-example/non-psr0-libraries": "dev-master",
    },
    "autoload":{
        "files": ["vendor/vendor-example/non-psr0-libraries/Library01.php"]
    }
}

Using the files key you can then use

$lib = new \Library01();

Use the classmap key when you need to load multiple files containing classes. The composer.json would be:

{
    "require": {
        "vendor-example/non-psr0-libraries": "dev-master",
    },
    "autoload":{
        "classmap": ["vendor/vendor-example/non-psr0-libraries/"]
    }
}

Composer will scan for .php and .inc files inside the specified directory configuring the autoloader for each file/class.

For more info you can check http://getcomposer.org/doc/04-schema.md#files and http://getcomposer.org/doc/04-schema.md#classmap

If you are under a namespace while creating the object, you must use the "\" (root namespace), otherwise you will use the Library01 class under the current namespace (if you have one, if you don't have one you'll get an error).



来源:https://stackoverflow.com/questions/16366663/zf2-autoloading-libraries-without-namespaces

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