yii2namespacesaliases

Yii2 custom component namespace


I have a component class located in the following path:

@backend/components/component-name/ComponentClass.php

and want to use default namespace for this class:

namespace backend\components;

I've tried to set aliases in my confing/main.php:

...
'aliases' => [
    '@backend/components' => '@backend/components/component-name'
],
...

but I know that's wrong decision, because it's broke the namespace logic for the other classes located in backend/components.

How can I set the same namespace backend\components for both classes in @backend/components and @backend/components/component-name?


Solution

  • I suggest to use composer autoloader for this task - it works fine even if you provide multiple possible paths for single class. Edit your composer.json autoload section to something like:

    "autoload": {
        "psr-4": {
            "backend\\": "backend/",
            "backend\\components\\": "backend/components/component-name/",
            ...
        }
    },
    

    And run in console:

    composer dump-autoload
    

    Make sure that you're loading composer autoloader in your index.php:

    require __DIR__ . '/../vendor/autoload.php';
    require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';