Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autoload classes without namespaces with Composer without reinstalling?

I just need to autoload some classes, and I don't like the psr-0 namespace insanity (no offense).

This used to work just fine in my project:

"psr-0": {
    "": [
        "app/controller/",
        "app/model/"
    ]
}

For some reason it doesn't work anymore, even though I'm using the same Composer version. I need it for a new project that is also using Silex. Could this be a conflict with Silex?

I know about the "classmap" option, but it's kind of useless because it requires that I run "composer install" every time I add a new class.

Any ideas?

like image 406
ChocoDeveloper Avatar asked Jul 28 '13 17:07

ChocoDeveloper


People also ask

How do you autoload with composer?

After you create the composer. json file in your project root with the above contents, you just need to run the composer dump-autoload command to create the necessary autoloader files. These will be created under the vendor directory. Finally, you need to include the require 'vendor/autoload.

What is psr4 autoload?

Overview. This PSR describes a specification for autoloading classes from file paths. It is fully interoperable, and can be used in addition to any other autoloading specification, including PSR-0. This PSR also describes where to place files that will be autoloaded according to the specification.

How do you autoload in PHP?

The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.

What is composer autoload file?

Composer is an application-level dependency manager for PHP. Dependency simply means libraries/packages your application depends upon. Apart from managing the dependencies, composer will also autoload the files needed for the application.


1 Answers

Try to use "primitive" JSON properties; not an array (like in your example). This works for me with psr-4 like you say, with "": "app/":

{
"autoload": {
    "psr-4": {
        "Robbie\\": "core/",
        "": "app/"
    }
},
"require": {
        "monolog/monolog": "1.2.*"
    } 
}

This gives me the Robbie namespace under the directory core, as an example of sources not controlled by composer, the 3rd party (vendor) Monolog namespace and my default or non-namespace for sources underneath the app directory.

After a composer update, all of them are available when including the generated autoload.php:

<?php    
require_once 'vendor/autoload.php';
// ...    
?>    
like image 87
raoulsson Avatar answered Oct 12 '22 22:10

raoulsson