How to observe all models implementing the interface in Laravel 5.1?

I have an audit class that extends the Eloquent model ...

class Audit extends Model {
}

I have a testable interface ...

interface IAuditiable {
    public function audit();
}

I have a trait that runs the interface and defines the relationship between the model and the audit ...

trait Auditable {
    public function audit(){
        return $this->hasMany('Audit');
    }
}

I have a model that extends the Eloquent Model that implements the interface and uses the trait ...

class Post extends Model implements IAuditable {
    use Auditable;
}

I would like to add functionality to createor updateauditing there whenever a Post model is created or updated. I solved this by registering an observer in the Mail who would catch the “saved” event and add a new audit.

However, in the end, there will be many models using the implementation IAuditableand use of the attribute Auditable.

, : , "" , IAuditable Laravel 5.1?

+4
1

. - :

Event::listen(['eloquent.created: *', 'eloquent.updated: *'], function($model) {
    // Check if the model implements your interface (could use class_implements(...)  
});

- , . , , .

EDIT: , . , -, :)

+1

Source: https://habr.com/ru/post/1618281/


All Articles