phpnamespacescomposer-phpautoloaderspl-autoloader

Composer autoload - How to fetch classes, traits, interfaces from different folders?


How can I use composer autoload to fetch classes, traits, interfaces from different folders?

Some of them I use namespaces, such as,

controller/Foo.php,

namespace MyNamespace;
class Foo
{
    public $message = 'hello Foo';
}

model/Boo.php

namespace MyNamespace;
class Boo
{
    public $message = 'hello Boo';
}

index.php,

// Composer.
require 'vendor/autoload.php';

use \MyNamespace\Foo;
$Foo = new Foo();
var_dump($Foo);

error,

Fatal error: Class 'MyNamespace\Foo' not found in C:...

composer.json,

{
    "autoload": {
        "psr-0": {
            "": "ext/",
            "": "controller/",
            "": "model/" 
        }
    }
}

I have many classes in many different folders (it may expand), so is there any way without re-installing composer autoload when I have new classes in a fresh folder?


Solution

  • You have to standardize your namespaces and folders structure. If you have the same namespace in different folders, it's harder to create a simple logic to autoload them all. Try to use another segment in your namespace like:

    namespace MyNamespace\Controller;
    class Foo
    {
        public $message = 'hello Foo';
    }
    

    and:

    namespace MyNamespace\Model;
    class Boo
    {
        public $message = 'hello Boo';
    }
    

    and in your composer.json:

    {
        //..
        "autoload": {
            "psr-4": {
                 "MyNamespace\\Model\\": "/path/to/model/folder/",
                 "MyNamespace\\Controller\\": "/path/to/controller/folder/"
            }
        }
    }
    

    after setting this up, call:

    composer dump-autoload