Namespace Alias in Laravel

为君一笑 提交于 2020-01-11 13:23:08

问题


I apologize if this is duplicate; please guide me to the right directions.

I know we can create class aliases in Laravel from /config/app.php. However trying to create namespace aliases using the same method fails.

    /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

    'aliases' => [
    ...

    /*
    *    My custom namespace aliases
    */
    'MyNamespace' => 'App\Models\MyNamespace',

    ],


Testing this in thinker returns the following results:

>> new \MyNamespace\MyClass();

PHP Fatal error:  Class 'MyNamespace/MyClass' not found in Psy Shell code on line 1

Do you know a way to create namespace alias in Laravel?


回答1:


Make your code PSR-4 compatible and put it in composer.json

"autoload": {
    "psr-4": {
      "MyNamespace\\": "src/MyNameSpace",
    }
},

Then run composer dumpautoload. So long as you stick to the convention of subfolders being namespaces, your classes will autoload.

src/MyNamespace/SomeClass.php would have namespace MyNamespace; and class SomeClass.

src/MyNamespace/Something/SomethingElse.php would have namespace MyNamespace\Something; and class SomethingElse.



来源:https://stackoverflow.com/questions/58731031/namespace-alias-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!