【问题标题】:Namespace Alias in LaravelLaravel 中的命名空间别名
【发布时间】:2020-03-02 23:44:26
【问题描述】:

如有重复,我深表歉意;请指导我正确的方向。

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

    /*
    |--------------------------------------------------------------------------
    | 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',

    ],


在 thinker 中对此进行测试会返回以下结果:

>> new \MyNamespace\MyClass();

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

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

【问题讨论】:

    标签: php laravel namespaces


    【解决方案1】:

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

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

    然后运行composer dumpautoload。只要你坚持子文件夹是命名空间的约定,你的类就会自动加载。

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

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

    【讨论】:

      猜你喜欢
      • 2014-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-18
      • 2019-01-02
      • 2023-03-21
      • 2015-07-27
      • 2016-11-27
      相关资源
      最近更新 更多