dimanche 30 juillet 2017

Laravel observer pattern for keeping two related models in sync

I'm using Laravel 5.4. I have two related eloquent models:

ImageFile and ClipartImage.

ClipartImage contains a belongsTo relationship as follows:

class ClipartImage extends Model
{
    public function image_file()
    {
        return $this->belongsTo(ImageFile::class, 'image_file_id');
    }

    public function promote()
    {
        $this->image_file->promote();
    }
}

On ClipartImage there is a "promote" method which will pass the promote call through to the ImageFile object as it knows how to promote itself.

The problem I'm running into is if things change on the underlying image file, there are a couple of properties on the related ClipartImage which may be affected. In the ImageFile class I could search the database for any related ClipartImages and update the relevant properties, but this doesn't update the ClipartImage instance already loaded and in memory that I am working with, so what's the best way to handle this in Laravel?

In other languages I'm used to I might define a xxxChanged event on the ImageFile class which the ClipartImage could subscribe to so it can update/refresh itself when required.

I guess I'm in need of some sort of Observer pattern but in Laravel these things seem to be handled at the static/class level not for individual object instances - ie I could create an observer class that looked for any changes to ImageFile models, but that isn't going to help me refresh or update my existing ClipartImage object is it?

If I was going to try and roll something custom - eg just have a property on ImageFile for currentClipartImageInstance so the ImageFile could call back to the ClipartImage instance to refresh it, I wasn't clear where I would add the hook - I thought of defining a mutator so I could add the hook after the relationship was set but I don't think that would work -eg if associate etc was used to establish a relationship.

Any advice on the normal way to handle this welcome I'm still fairly new to Laravel and worried I'm missing something simple here.

Edit: Please note that while I've distilled this down to a single promote method to illustrate the point, there's a bunch of interaction between ClipartImage and the underlying file class and it's not obvious from the point of view of ClipartImage when it may need to refresh or make changes to itself, mostly it won't as I've tried to segregate things as much as I can into their respective classes - reading back the example it seemed like the obvious solution might be to do some sort of refresh after the promote call, but I'm looking for something a bit more generic as there are lots of such calls.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2vkaHFM
via IFTTT

Aucun commentaire:

Enregistrer un commentaire