gpt4 book ai didi

php - Laravel 事件不起作用

转载 作者:行者123 更新时间:2023-11-29 12:29:01 25 4
gpt4 key购买 nike

我设置了一个事件,该事件在用户注册后执行一些操作。更新和插入等,但不起作用。

我收到错误:

Symfony\Component\Debug\Exception\FatalErrorException (E_ERROR)未找到“EventHandlers\Handlers\User”类

我不知道为什么它不起作用。但我没有拼写任何错误,因为如果我例如“return 'test';”在我看来,它可以工作,但不会更新我的 userModel

在我的用户 Controller 中:

$user = User::create([

some values..

]);


Event::fire('user.create', $user);

现在我订阅了 app/start/global.php 中的事件,我使用 PSR-4 自动加载该文件夹

Event::subscribe('EventHandlers\Handlers\UserAccountActions');
Event::subscribe('EventHandlers\Handlers\ProductActions');
Event::subscribe('EventHandlers\Handlers\CommentActions');

在我的事件/监听器文件中

<?php namespace EventHandlers\Handlers;

class UserAccountActions {

// Listeners
public function subscribe($events)
{
$events->listen('user.create', 'EventHandlers\Handlers\UserAccountActions@onCreate');
}

// happens when a user register
public function onCreate($user)
{
$user->api_key = User::createApiKey();
}

}

最佳答案

在您的 EventHandlers\Handlers\UserAccountActions 中,您引用 User,因为它位于同一命名空间中。您需要添加反斜杠 \ 来访问全局命名空间中的 User 类:

// happens when a user register
public function onCreate($user)
{
$user->api_key = \User::createApiKey();
}

(或者如果 User 模型位于其中,则指定命名空间。例如 \Models\User)

或者,您也可以使用 use 语句导入模型:

use User;

class UserAccountActions {

关于php - Laravel 事件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27881715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com