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

Regarding the question Passing default variables for viewing , to pass variables available to all views, is there a technical or functional difference between using View::composer()

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

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

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

I only recently found out about View::share() and found it exclusively encrusted, although I had already started using the first in another project.

Edit:

My first assumption is that the first file (filters.php) and the last is a class (BaseController.php). With that in mind, I assume the class is much better? Although, I do not quite understand why at the moment. :)

+6
source share
2 answers

Technically, they are completely different. View::share simply sets the variable, and View::composer is a callback function.

Let me explain in more detail:

View::share really straightforwardly sets a variable that can be used in any of the views, think of it as a global variable.

View::composer logs an event that is raised when a view is rendered, do not confuse it with View::creator , which is fired when an instance is created.

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

Although they give you the ability to pass additional data into the view, they also give you the ability to do many other things, for example, they could:

  • Help debugging a view
  • Register viewing information
  • Use to create custom caching (maybe this is not a good idea, but possible)

These are just some examples of what could be used with View::composer and View::creator .

+13
source
 View::composer('*', callback()); 

means that the callback will be called for all views (*).

 View::share 

Indicates that the variable will be shared with all displayed views.

Because the first is in filter.php, it will be applied to all routes.

The second is in the controller, so it will be applied to all views initiated by this controller.

Last: when redefining a constructor, this is a good paradigm for invoking a parent constructor using this code:

 parent::_construct(); 
0
source

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


All Articles