2017-06-14 137 views
0

我在我的项目中使用雄辩(我不使用Laravel),它可以像预期的那样开箱即用。只有问题,我无法在模型上设置事件。Laravel雄辩5.4模型事件

例如:我想做些别的事情更新模型时,或当事情被保存在模型等。

这段代码在雄辩5.4还工作吗?我做了一些尝试,但失败了。可能这不再适用Eloquent 5.4我需要一个替代方案。

class Something extends Model { 
    public static function boot() { 
     parent::boot(); 
     static::creating(function($item) { 
      $item->uuid = uuid_generate(); 
     }); 
    } 
} 

如果不是,我需要一个不是Laravel方式的解决方案。希望它有可能在模型本身内部捕获这些事件。

+0

应该可能工作,但首选的方式已经改变。看看这里的文档:https://laravel.com/docs/5.4/eloquent#events –

+0

事件将被解雇,但你将需要注册一个调度员,实际上做这些事件的事情,因为你不是在Laravel中使用雄辩。 –

+0

上面的代码不起作用,有没有办法做到这一点,并保持简单?我需要写这个调度员? –

回答

0
use Illuminate\Database\Capsule\Manager as Capsule; 

$capsule = new Capsule; 

$capsule->addConnection([ 
    'driver' => 'mysql', 
    'host'  => 'localhost', 
    'database' => 'database', 
    'username' => 'root', 
    'password' => 'password', 
    'charset' => 'utf8', 
    'collation' => 'utf8_unicode_ci', 
    'prefix' => '', 
]); 

// Set the event dispatcher used by Eloquent models... (optional) 
use Illuminate\Events\Dispatcher; 
use Illuminate\Container\Container; 
$capsule->setEventDispatcher(new Dispatcher(new Container)); 

// Make this Capsule instance available globally via static methods... (optional) 
$capsule->setAsGlobal(); 

// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher()) 
$capsule->bootEloquent(); 

作曲家,当你需要使用观察家雄辩的要求“亮/事件”要求。

您需要在这样的外部项目中设置Eloquent以供事件和观察者工作。

设置活动:

class Something extends Model { 
    public static function boot() { 
     parent::boot(); 
     static::creating(function($item) { 
      $item->uuid = uuid_generate(); 
     }); 
    } 
} 

class Something extends Model { 
    protected $events = [ 'created' => createdEvent::class] 
} 

检查文档的详细,但两种方式在洋洋洒洒5.4仍然有效。