0

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.