1

By considering this files structure

| -- src / | -- vendor | -- models | -- libraries | -- ... | -- composer.json 

How can I autoload classes located in 'models' & 'libraries' directories ?

2
  • 1
    You typically include two autoloader files / implementations: the one created by composer and your own. Commented May 5, 2017 at 11:05
  • I was thinking that PHP allows only one autoloader (I don't know from where this idea comes !), I test the two autoloaders and they work fine, thanks Commented May 5, 2017 at 11:27

2 Answers 2

5

You can add your own autoloader rules into the composer.json file in your project - this adds your own rules to the vendor/autoload.php file so that your own classes will load as well as the ones in the vendor/ directory. There's more information in the docs here: https://getcomposer.org/doc/04-schema.md#autoload. Take a look at the PSR-0 section to load classes from your two directories.

Try something like:

{ "autoload": { "psr-0": { "": ["models/", "libraries"] } } } 

If your classes are namespaced, then specify the namespaces as this will stop composer from looking for all classes in those directories.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't know why but things don't want to work with "psr-0", but it works fine with psr-4: "psr-4": { "namespace1\\": "models/", "namespace2\\": "libraries/" } ... thanks
0

Or later in code you can add your lib, example:

$loader = require(ROOTDIR . 'vendor/autoload.php'); // composer autoloading //public function addPsr4($prefix, $paths, $prepend = false) $loader->addPsr4('extend\\', ROOTDIR . 'class/lib'); $a = new \extend\MyClass(); // MyClass.php is in ROOTDIR/class/lib directory 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.