vendredi 6 novembre 2015

Laravel service provider overwriting variables

I am in the process of trying to simplify one of my Laravel 5.1 controllers by using a service provider, since I have the same data sent to many views. However, those views have many partials that also use the same data. The partials don't have any problem getting the data from the controller, but when I try to use a service provider instead, the partials seem to all need the data as well.

For example, in my controller I had:

public function oneView(){
   $data = $thisData();
   return view('myView', compact('data'));
}

public function twoView(){
   $data = $differentData();
   return view('anotherView', compact('data'));
}

Now in my service provider, I can do this instead:

class ViewComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->composeMyView();
        $this->composeAnotherView();
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    public function composeMyView()
    {
        view()->composer(['myView', 'myView2', etc...], function ($view) {
            $data = $thisData();
            $view->with(compact('data'));
        });
    }

    public function composeAnotherView()
    {
        view()->composer('anotherView', function ($view) {
            $data = $differentData();
            $view->with(compact('data'));
        });
    }
}

I have something like 50 partials that each give a "undefined variable" warning, and so I must include them one by one (so that the above line in the service provider becomes view()->composer(['anotherView', 'partialOne', 'partialTwo', 'partialThree', etc.]).

The end result is that the code isn't really more efficient this way than the way I was doing it before.

Plus, there is another problem where I have the same partials making up both of the above views, and I suspect this will result in the first $data variable getting overwritten by the second $data variable no matter which view is being used, just like if I were to try using '*' to give the $data variable to all views in the service provider (which I did try doing, and the 2nd $data variable did overwrite the first one).

I'm thinking perhaps there is a better way to do the above and hoping someone can shed some light for me.

Adding a helper method to the Controller that returns an array of all the data I need for each view seems to be the best solution I can think of to minimize repetition at this point, but I'd prefer to use the service provider the right way if I'm missing something.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire