Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Difference between View::share() and View::composer()

Tags:

php

laravel

view

In relation to the question Passing default variables to view, to pass variables available among all views, is there a technical or functional difference between the use of View::composer():

View::composer('*', function($view) {
    $thundercats = 'Woooooohh!!';
    $view->with('thundercats', $thundercats);
})

in the filters.php file or the use of View::share() in the BaseController.php file:

public function __construct {
    $thundercats = 'Woooooohh!!';
    View::share('thundercats', $thundercats);
}

I've only recently learned about View::share() and find it exceptionally intruiging although I've already started using the former in another project.

Edit:

My first assumption is that the former is a file (filters.php) while the the latter is a class (BaseController.php). With this in mind, I'm guessing a class is much better? Although, I'm not quite sure why at this point. :)

like image 223
enchance Avatar asked Aug 19 '13 14:08

enchance


People also ask

What is View Composer in Laravel?

View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.

Where are views stored in Laravel?

Views are stored in the resources/views directory. return view('greeting', ['name' => 'James']); }); As you can see, the first argument passed to the view helper corresponds to the name of the view file in the resources/views directory.

What is views in Laravel?

It separates the application logic and the presentation logic. Views are stored in resources/views directory. Generally, the view contains the HTML which will be served by the application.


1 Answers

Technically they are not at all alike. View::share simply sets a variable, while View::composer is a callback function.

Let me explain in greater detail:

View::share is really straight forward it sets a variable which can be used within any of the views, think of it like a global variable.

View::composer registers an event which is called when the view is rendered, don't confuse it with a View::creator which is fired when a view is instantiated.

View::composer / View::creator can both be used as a class which is well documented.

While these give you the ability to pass additional data to a view, they also give you to ability to do a lot of other things, for example they could:

  • Aid in debugging a view
  • Log information about views
  • Be used to create custom caching (probably not a great idea, but possible)

These are just some examples of what could be possible using View::composer and View::creator.

like image 163
tplaner Avatar answered Oct 28 '22 10:10

tplaner