mercredi 16 mai 2018

Middleware before Model injection

I have a design doubt I would like to share.

I have a model in Laravel with an Observer at retrieved:

class MailingObserver
{
    public function retrieved($mailing)
    {
      // we retrieve HTML content from disk file        
      $mailing->setAttribute('content', \Illuminate\Support\Facades\Storage::disk('mailings')->get("{$mailing->id}-{$mailing->slug}.html"));
      $mailing->syncOriginal();
    }
}

which retrieve an attribute stored in a plain text instead of database.

The site is a multibrand platform so disk('mailings') is different per each logged user. This configuration is loaded in a middleware according to the the current logged user.

Up to here all is fine.

Now the "problem". I have a Controller which injects the entity Mailing:

class MailingCrudController extends CrudController
{
    /**
     * Sends the mailing
     * @param Request $request
     * @param \App\Mailing $mailing
     */
    public function send(Request $request, \App\Mailing $mailing)
    {
       // WHATEVER
    }
}

When the model is injected the retrieved Observer method is fired but the Middleware wasn't still executed so mailings disk is still not set up.

I don't know how to change this order: first execute middleare, then the model injection.

One approach

I tried in AppServiceProvider to add:

class AppServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {   
        $middleware = new \App\Http\Middleware\CheckBrandHost();
        $middleware->setBrandInformation(request());
        $middleware->loadBrandConfig(request()->get('brand.code_name'));
    }

Would you approve this solution? What problems can cause it to me? Is it the proper way to do it?

Thanks all!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire