在观察者中聆听雄辩的模型事件

时间:2015-05-09 14:08:53

标签: php laravel laravel-4

我找不到在我的事件处理程序中侦听雄辩事件的语法。

我订阅了我的观察者

Event::subscribe('Animekyun\Handlers\Events\EloquentEventHandler');

这个观察者是自我处理的,并且实现如下:

namespace Animekyun\Handlers\Events;

use Illuminate\Events\Dispatcher;

class EloquentEventHandler
{

    public function onEpisodeSave($event) {
        dd('test');
    }

    public function subscribe(Dispatcher $events)
    {
        $events->listen('eloquent.saved: episode', 'Animekyun\Handlers\Events\EloquentEventHandler@onEpisodeSave');
    }

}

我不知道如何倾听这种形式的任何雄辩事件。我确信有一种方法可以在不执行以下操作的情况下收听事件:

User::creating(function($user)
{
    if ( ! $user->isValid()) return false;
});

编辑: 用户模型

<?php

use Laracasts\Presenter\PresentableTrait;
use Conner\Likeable\LikeableTrait;

class Episode extends \Eloquent
{
    use PresentableTrait;
    use LikeableTrait;

    public static $rules = [
        'show_id'        => 'required',
        'episode_number' => 'required',
    ];

    // Add your validation rules here
    protected $presenter = 'Animekyun\Presenters\EpisodePresenter';

    // Don't forget to fill this array
    protected $fillable = ['title', 'body', 'links', 'show_id', 'episode_number', 'format_id', 'created_by', 'updated_by', 'screenshots'];

    public function scopeSearch($query, $search)
    {
        return $search;
    }

    public function user()
    {
        return $this->belongsTo('User', 'created_by');
    }

    public function show()
    {
        return $this->belongsTo('Show');
    }

    public function format()
    {
        return $this->belongsTo('Format');
    }

    public function rating()
    {
        return $this->morphMany('Rating', 'rateable');
    }

    public function getLinksAttribute()
    {
        return (array) json_decode($this->attributes['links'], true);
    }

    public function setLinksAttribute($value)
    {
        $this->attributes['links'] = json_encode($value);
    }
}

任何想法?

1 个答案:

答案 0 :(得分:1)

你正在听错事件。由于字符串比较区分大小写,因此您应该收听eloquent.saved: Episode事件。请注意E上的首都Episode。事件被触发时,类名不会转换为小写。

此外,虽然这不适用于您的特定情况,但应注意,如果类在命名空间下定义,例如App,则还需要包含该命名空间(即{ {1}})。

相关问题