简体   繁体   English

没有从CLI(Laravel外)发射的雄辩事件

[英]Eloquent event not firing from CLI (outside Laravel)

I have the following event handler in my model: 我的模型中有以下事件处理程序:

<?php
namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    //...

    public static function boot()
    {
        parent::boot();

        static::saving(function ($user) {
            // die('inside');
            if (empty($user->username)) {

                $base = strtolower($user->first_name . '.' . $user->last_name);

                do {
                    $username = $base . @$suffix;
                    $duplicate = User::where('username', '=', $username)->first();
                } while($duplicate and $suffix = rand(1000, 9999));

                // return the original/ generated username
                $user->username = $username;
            }
        });
    }
}

Basically when username is not set, the model will automatically generate a unique username from the first/last name. 基本上,当未设置用户名时,模型将自动从名字/姓氏生成唯一的用户名。 This works fine in the browser. 这在浏览器中工作正常。 But not in the CLI when I'm running my tests - username is not set, so it attempts to insert without username which my mysql table doesn't accept. 但是当我运行我的测试时没有在CLI中 - 没有设置用户名,所以它试图插入没有我的mysql表不接受的用户名。

Below is how I'm setting up Eloquent console: 以下是我如何设置Eloquent控制台:

$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection([
            'driver' => 'mysql',
            'host' => 'localhost',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'database' => 'sso_dev',
            'username' => 'root',
            'password' => 'vagrant1',
        ]);
$capsule->setEventDispatcher( new \Illuminate\Events\Dispatcher( new \Illuminate\Container\Container ));
$capsule->bootEloquent();
$capsule->setAsGlobal();

Both the web environment and testing use this same code. Web环境和测试都使用相同的代码。 If I comment the line setEventDispatcher then the browser environment throws an error as the event handler doesn't fire. 如果我对setEventDispatcher行进行setEventDispatcher那么浏览器环境会抛出错误,因为事件处理程序不会触发。 So I know the event dispatcher is doing it's job there. 所以我知道事件调度员正在那里做它的工作。 Just not the testing CLI environment. 只是没有测试CLI环境。 Any reason why this might be? 这可能是什么原因?

Btw I'm using Eloquent 5.3. 顺便说一下,我正在使用Eloquent 5.3。

You will need to make a call to the setEventDispatcher again when it boots. 启动时,您需要再次调用setEventDispatcher。

public static function boot(){
    parent::boot();

    static::setEventDispatcher(new \Illuminate\Events\Dispatcher());
    static::saving(function ($model){
        // now you can reference your model
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM