Laravel中的命名空间别名 [英] Namespace Alias in Laravel

查看:57
本文介绍了Laravel中的命名空间别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是重复的,我深表歉意;请指导我正确的方向.

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

我知道我们可以从/config/app.php在Laravel中创建类别名.但是,尝试使用相同的方法创建名称空间别名失败.

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


您知道在Laravel中创建名称空间别名的方法吗?


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

推荐答案

使您的代码PSR-4兼容并将其放入composer.json

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

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

然后运行composer dumpautoload.只要您遵循子文件夹即名称空间的约定,您的类就会自动加载.

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

src/MyNamespace/SomeClass.php将具有namespace MyNamespace;class SomeClass.

src/MyNamespace/Something/SomethingElse.php将具有namespace MyNamespace\Something;class SomethingElse.

这篇关于Laravel中的命名空间别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆