Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Composer's Autoload

I have been looking around the net with no luck on this issue. I am using composer's autoload with this code in my composer.json:

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

But I need to autoload at a higher level than the vendor folder.

Doing something like this does not work:

"autoload": {     "psr-0": {"AppName": "../src/"} } 

Does anyone know a fix or how I can do this?

like image 455
Chris R Avatar asked Oct 10 '12 11:10

Chris R


People also ask

What does composer dump autoload do?

Composer dump-autoload: The composer dump-autoload will not download any new thing, all it does is looking for all the classes and files it needs to include again.

How does PHP autoload work?

The PHP Autoloader searches recursively in defined directories for class, trait and interface definitions. Without any further configuration the directory in which the requiring file resides will be used as default class path. File names don't need to obey any convention. All files are searched for class definitions.

What is autoload PHP file?

Autoloading is the process of automatically loading PHP classes without explicitly loading them with the require() , require_once() , include() , or include_once() functions. It's necessary to name your class files exactly the same as your classes. The class Views would be placed in Views.


2 Answers

Every package should be responsible for autoloading itself, what are you trying to achieve with autoloading classes that are out of the package you define?

One workaround if it's for your application itself is to add a namespace to the loader instance, something like this:

<?php  $loader = require 'vendor/autoload.php'; $loader->add('AppName', __DIR__.'/../src/'); 
like image 122
Seldaek Avatar answered Oct 07 '22 08:10

Seldaek


The composer documentation states that:

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

Assuming your "src" dir resides at the same level as "vendor" dir:

  • src
    • AppName
  • vendor
  • composer.json

the following config is absolutely correct:

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

but you must re-update/install dependencies to make it work for you, i.e. run:

php composer.phar update 

This command will get the latest versions of the dependencies and update the file "vendor/composer/autoload_namespaces.php" to match your configuration.

Also as noted by @Dom, you can use composer dump-autoload to update the autoloader without having to go through an update.

like image 21
Sergiy Sokolenko Avatar answered Oct 07 '22 09:10

Sergiy Sokolenko