Norway


for another new feature in 5.3!

Shortcut helpers in Laravel

As I was writing my book I noticed a pattern in the global functions like session() and, in some ways, cookie(). There are three functions that they can perform: get a value, put a value, or return an instance of their backing service.

For example:

  • session('abc', null) gets the value of abc, or an optional fallback of null.
  • session(['abc' => 'def']) sets the value of abc to def.
  • session() returns an instance of the SessionManager.

The third option means you can use session()->all() (or any other methods) just like you would Session::all().

I mentioned that it seems like there should be a () helper, and before I could even think much more about it, Jeffrey (Way) had already written one up. So! Behold! The global cache() helper, new in Laravel 5.3.

The cache() global helper

Like session(), the cache() global helper can perform three primary functions: get, put, or return an instance of the backing service.

For example:

  • cache('abc', null) gets the cached value of abc, or an optional fallback of null.
  • cache(['abc' => 'def'], 5) sets the value of abc to def, for the duration of 5 minutes.
  • cache() returns an instance of the CacheManager.

The third option means you can use cache()->forever() (or any other methods) just like you would Cache::forever().

That’s it! Enjoy!



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here