Moose Moose
Moose Moose

Reputation: 267

Own project via composer

I've got some libraries loaded through composer, and I'm wondering if it's possible to add my own library in the /vendor map, and then to have the composer autoloader load it? The structure would be something like /vendor/mylibrary/ and then a namespace mylibrary.

Would this be possible? Also would it be possible to add a different map to the composer autoloader? Like for example /app/src/ and then to have it load all the classes in that folder? Or do I have to make my own loader for that?

Thanks

Upvotes: 8

Views: 3334

Answers (3)

kta
kta

Reputation: 20110

Yes.You can achieve it. Configure your composer.json file as following:

{
    "autoload": {
        "classmap": [ "classes" ]
}

Here classes is the name of the directory where you have all your application related classes.Vendor related class should be auto detected as well. Just add the following line to achieve both at the same time:

require 'vendor/autoload.php';

And you can use the namesapce to reference your class like the following:

use classes\Model\Article; 

Upvotes: 2

Alexander M. Turek
Alexander M. Turek

Reputation: 576

Yes, of course it is possible to add own libraries and you should feel highly encouraged to do so. If your library is available publicly, you can simply register it at packagist.org. If not, it's a bit more complicated, but not impossible.

If your project does not follow the PSR-0 standard, composer will create a classmap for you. A custom autoloader is not supported.

I'd recommend you to read the (really excellent) documentation about all this and come back, if you're running into problems.

http://getcomposer.org/doc/

Upvotes: 1

Jose Armesto
Jose Armesto

Reputation: 13749

Reading the composer documentation:

You can even add your own code to the autoloader by adding an autoload field to composer.json.

{
    "autoload": {
        "psr-0": {"Acme": "src/"}
    }

}

Composer will register a PSR-0 autoloader for the Acme namespace. You define a mapping from namespaces to directories. The src directory would be in your project root, on the same level as vendor directory is. An example filename would be src/Acme/Foo.php containing an Acme\Foo class.

After adding the autoload field, you have to re-run install to re-generate the vendor/autoload.php file.

So basically, you just need to follow PSR-0, and tell composer where to find your library, by adding that line to your composer.json

Upvotes: 7

Related Questions