Laravel: Difference between View::share() and View::composer()
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
.
View::composer('*', callback());
Means that the callback will be called for all views (*).
View::share
Means that a variable will be shared with all outputed views.
Because the first is in filters.php, it'll apply for all routes.
The second is in a controller contructor, so it'll apply for all views triggered by this controller.
One last thing: when overriding a constructor, it's a good pratice to allways call the parent constructor with this code:
parent::_construct();