【问题标题】:Laravel Events and ListenersLaravel 事件和监听器
【发布时间】:2020-11-29 19:37:00
【问题描述】:

这是我使用时的事件类

class EventServiceProvider extends ServiceProvider
    {
        /**
         * The event listener mappings for the application.
         *
         * @var array
         */
        protected $listen = [
            Registered::class    => [
                SendEmailVerificationNotification::class,
            ],
            CategoryEvent::class => [
                CategoryCreatedListener::class,
            ]
        ];

当我运行以下命令时

php artisan event:generate

如果我将命名空间放在事件和监听器之前,它会在服务提供者目录中创建事件和监听器

App\Events\CategoryEvent::class

它仍然在Service Provider Directory 中创建App\Event 和App\Event 如何在App Namespace 中创建Event 和Listener Directory。

【问题讨论】:

    标签: laravel laravel-7 laravel-events


    【解决方案1】:

    听起来像是命名空间问题。您可能需要确保这些类具有别名:

    use App\Events\Registered;
    use App\Listeners\SendEmailVerificationNotification;
    ...
    

    否则Registered::class 将是App\Providers\Registered

    【讨论】:

    • 谢谢,我搜索了谷歌并找到了解决方案并为我工作。 event_name 和侦听器名称需要用引号引起来,并且不需要 event_name::class 部分。但是 Pycharm 建议它应该像 **event_name::class' 但它适用于该警告。
    • nothing has 是字符串文字,您在使用Class::class 时没有引用正确的类,因此出现了命名空间问题\App\Events\Registered::class === 'App\Events\Registered'
    【解决方案2】:

    Laravel 似乎没有对事件生成的自定义路径支持。所以你最好的选择可能只是在你想要的目录中手动创建它,然后自己将它插入到 EventServiceProvider 中。这有点手工工作,但不会超过一分钟。

    类似的问题已经解决了:How do I create Events/Listeners with artisan command at sub-directory level?

    【讨论】:

    • @ServerinDK 我找到了解决方案,感谢您的帮助。我认为问题出在语法上,因为旧版本使用与 laravel 7 不同的语法,而且我没有在旧版本中工作过,所以这就是为什么会遇到这些问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 2020-05-06
    相关资源
    最近更新 更多