ZF2: autoloading libraries without namespaces

2019-02-18 06:08发布

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条回答
我只想做你的唯一
2楼-- · 2019-02-18 06:28

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).

查看更多
登录 后发表回答