dongxixia6399
2017-12-14 06:57
浏览 62
已采纳

如何在Laravel 5.5中实现事件

The Laravel Eloquent Event docs give this example:

namespace App;

use App\Events\UserSaved;
use App\Events\UserDeleted;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The event map for the model.
     *
     * @var array
     */
    protected $dispatchesEvents = [
        'saved' => UserSaved::class,
        'deleted' => UserDeleted::class,
    ];
}

I simply want to know what would go in a UserSaved::class to, let's say, add a hash id on the initial save. The docs are frustratingly opaque at this point!

图片转代码服务由CSDN问答提供 功能建议

Laravel Eloquent Event 文档给出了这个例子:

  namespace App; 
 
use App \ Events \ UserSaved; 
use App \ Events \  UserDeleted; 
use Illuminate \ Notifications \ Notifiable; 
use Illuminate \ Foundation \ Auth \ User as Authenticatable; 
 
class User extends Authenticatable 
 {
 use Notifiable; 
 
 / ** 
 *活动地图 对于模型。
 * 
 * @var数组
 * / 
 protected $ dispatchesEvents = [
'saved'=>  UserSaved :: class,
'deleted'=>  UserDeleted :: class,
]; 
} 
   
 
 

我只是想知道 UserSaved :: class 会发生什么 比方说,在初始保存中添加哈希id。 在这一点上,文档令人沮丧地不透明!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dousao2186 2017-12-14 07:12
    已采纳

    In any of your model event classes, just do this:

    For example: App\Events\UserSaved.php

    <?php
    
    namespace App\Events;
    
    use Illuminate\Queue\SerializesModels;
    
    class UserSaved
    {
    
        use SerializesModels;
    
        /**
         * @var \App\User
         */
        public $user;
    
        public function __construct($user)
        {
            // All dispatched model events will receive an instance
            // of the model itself. Usually, we'll just assign
            // it as a property of this event class
            $this->user = $user;
        }
    }
    

    Dispatched event are supplied with the model instance, as shown in the source code:

    Documentation: Defining Events

    So at the later time when your listeners caught this event, they will have an instance of this UserSaved object, and you can just access user from $userSaved->user.

    点赞 打赏 评论
  • dqtiober37522 2017-12-14 07:10

    It would be an event class, it takes the current model the event is being fired for in its constructor.

    "An event class is simply a data container which holds the information related to the event. " Laravel 5.5 Docs - Events - Defining Events

    You will need to setup a listener to listen for your custom event object you are now firing instead of the eloquent string event it would normally fire. In the listener(s) you can react to this event.

    点赞 打赏 评论

相关推荐 更多相似问题