问题
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