Laravel 5: Cache – How to use it

Laravel 5: Cache – How to use it


Cache: keep popular stuff handy.

All cache commands can be found here (5.3).

Here are some most popular.

Using Cache facade
Retrieve & Store

This is probably the most useful of them all, as you do not have to run any checks yourself.

You are trying to get cache for key ‘users’.

  • if it exists, you are
    • getting your stored instance in $value variable
    • you are not getting inside of closure, since your cache is available and still valid
  • if it does not exist, you are
    • getting instance from database (command inside of closure),
    • you are storing it in cache
    • $value variable returns it for you to use

Variable $minutes tells cache for how long to store cached value.
It is in minutes.
e.g. 24*60 would indicate storage for 24 hours.

If you want to pass some variable into closure, this is how it is done:

You can use tags with closure like this:

Above is useful, if you use model name as tag, so when updating data for given model, you can just flush cache for given model only.
This way you do not have to remember, what is cached and needs to be refreshed on update.
Just flush model(s) being updated and if you properly used closure, it will be auto repopulated, if missing (flushed).
IMPORTANT – TAGS

Laravel cache tags are really indexes.
Just like in arrays.

So, if you do this:

… to read it, you HAVE TO do this:

NOT this:

Second option  will get you null.
Of course above applies to remember() as well, not only rememberForever().

What tags are really good at is to streamline deleting – flushing() many cache keys wholesale.

So, if you have these two cache keys – users and affiliates:

… you can get rid of them in one line of code:

 

Checking For Item Existence

With some other commands, you should check, if cache holds key you look for.
If key does not exist, you will get null in return.
You can use has command here, so you can store missing value (if this is desired) and get some not null return, e.g.:

We could also use DateTime via Carbon instead passing minutes as integer

Retrieve & Delete

If you want to get value from cache and remove it at the same time, you can:

Retrieve data by key

If you want to retrieve data by key without checking anything, you can use get.

If you want to get some value, if key is not found in cache, you can specify default value:

Above is good for some simple values. Values you already have handy in a code-flow, or some arbitrary values.
Getting some data from database would not fit cache scenario at all – because why looking into cache at all?
Using has condition is better. Even better to use remember command.
But of course all depends on current situation.

You can also use Closure:

Storing Items In The Cache

Above value will be stored for 10 hours.

Store, if key is not present

Will do nothing, if key is in cache.
Returns bool.

Storing Items Forever

If you store forever, stored data will never expire.
You need to use forget method to remove it.

Remove from cache item by key

Use pull, if you want to retrieve value for further use.

Clear entire cache

This will remove all data from cache.
Since you can share caching engine for different apps – using prefixes – see: config\cache.php – careful with this method, as it will get rid of all data cached by engine. All prefixed caches will be destroyed.

Cache global helper function

Besides Cache facade, there is also cache() helper function available since Laravel 5.3.

Retrieval

Storage

 

Laravel 5: Cache – Why caching and what?

Laravel 5: Cache – Why caching and what?


Cache: caching adds speed to your app.

Making your app faster

Caching can speed up your app, if used in a good way.

Here are some numbers.

No cache

Cache: file

Cache: memcached

Cache: Redis

More about details, where above numbers came from in this article.

Caching is not always a good thing

As anything, caching has overhead.
So, if you cache small data chunks, it may not save time at all.

When to cache

It shines, when you are caching larger, repetitively used chunks of data.

Example: paging.

You can setup different cache stores for different paging constraints, like paging for given product type.
You can even give to such cache stores automated names depending on user selections.
Since paging is a repetitive task and involves large and repetitive datasets, cache is a perfect solution.

 

Laravel 5: Cache – General

Laravel 5: Cache – General


Cache: Types and setup.

Cache engines

Laravel come with its unified API that works with some popular caching engines:

I am going to take a look at some of them in detail and I am going to report any ‘gotchas’ and peculiarities I discover.


Memcached

I am not a big fan of memcached.

But that’s just my opinion and most likely I am biased as hell.
But just think this: why setting up yet another tool (memcached), if some other tool (redis) used all over Laravel in queues, broadcasting, and also in cache can do the same?


Interesting thing is with Redis.

Given that Laravel unified cache API services redis,  why use memcached and have to set it up and maintain.
And since redis is used by Laravel in plenty other places (read below), why not use it also for a distributed cache as well. You have to set it up once and you can use it everywhere you need it.
Just read here – and you will see that redis pretty much is as good as memcached, but can do so much more.

So, where Laravel uses redis :

  • queues
  • cache
  • broadcasting
  • and you can also use it as fast key:value database with capacity to persist data – something memcached is not capable to do
Setting up Redis – see here.
Note

Laravel offers PhpRedis  (see also here) and Predis.
Both scripts provide the same access wrapper to Redis server.
PhpRedis is written directly in C, while Predis is written in PHP, so in some cases Phpredis is faster.

How much faster?
Well Aleksey Korzun took his time to run some benchmarks and here are the results.


As to APC – Alternative PHP Cache.

I have my doubts about using it.
It used to be great, but these days we need more.
Plus APC was discontinued and replaced by APCu.

Just read this and google up the rest.
And decide for yourself.


Array, file, database

Array

Array is for testing.
It is actually good for Tinker, if you are using it. I do not.
Do not get me wrong, Tinker is great, but I have never learned to enjoy console based tools for simulating and testing. Probably because I am windows man 😉

File

This is default Laravel setting.
All cached data is serialized and stored on server in form of a file(s).
It is good for small site, but if you can crack redis open, why not setting your project on proper foundation.

Especially, that once you setup redis, you can use it in so many other important places.
See above for where.

Of course, given Laravel unified cache API, you can always theoretically switch to redis later.
I am saying theoretically, because:

  • I have not tested that on data loaded (existing) project
  • I have more than once been unpleasantly surprised, that something which should work, proved not to for one, or another (sometimes silly, but hard to find) reason.

So, what if Laravel’s unified cache API fails you and you’re going to see that your project disintegrates on your testing server after you switch driver?

Measure your project and try to pick tools that can handle expected load from the jump start.
Best advice anyone can give you.

Database

Even with all this query and dynamic content caching, your database is one of hardest working elements of your site.
So, why putting that proverbial straw that can break you SQL’s back?
Especially that you have redis available.

 

Laravel 5: Background processes checklist

Laravel 5: Background processes checklist.


Laravel project involves a bit more than PHP code.
Here is the list, what you need to remember, when setting your app.


Checklist: Windows Environment Variable Path

Some software must (should) be added to Windows environment Variable Path.

Read more here.

Also, see this sample of ‘variable value’ in this text file.

Checklist 1: cron

Setup Cron, or for Windows (e.g. for dev) equivalent pseudo-Cron using task scheduler.
More here.

Difference is in: “Go to TAB: Actions, and click ‘New’ button” #2.

Each Laravel project needs separate cron setup in Windows task.
E.g. in example (link here above) I have: U:\www\la4\artisan.
Above path will make cron run only for project located in /la4 folder.
So, each folder/project needs own cron to work.

Above does not apply to Redis.
Explanation above apply to Windows dev setup.

Also see screenshots with how to setup Windows task: zip-file

 


Checklist 2: Redis

You need to install and start Redis server – if you are using it.
And since Redis can help in queues, cache, broadcasting and as database – it is worthwhile to install it.

For Linux, see here.

For Windows, see here and scroll down to: “setup Windows task”.
It uses same methodology as Cron. Anyway, all links are there.

Dependencies:

  • ioredis
  • predis

Also see screenshots with how to setup Windows task: zip-file

 


Checklist 3: Queues

If you are using queues other than ‘sync’, e.g. QUEUE_DRIVER=redis, then you need php artisan queue:listen command running. Eventually, you may use something like php artisan queue:work –sleep=3 –tries=3 .

For quick testing, you can run it in your console/command prompt, but to have it run all the time – also for dev, it is better to have daemon on Linux/Unix (OSX), or Task on Windows.

Linux setup – see here.

Windows setup – see here.

There is some difference thou to “Windows setup” description above:

Difference is in: “Go to TAB: Actions, and click ‘New’ button” #2.

Each Laravel project needs separate cron setup in Windows task.
E.g. in example (link here above) I have: U:\www\la4\artisan.
Above path will make cron run only for project located in /la4 folder.
So, each folder/project needs own cron to work.

Above does not apply to Redis.
Explanation above apply to Windows dev setup.

NOTE:
Queues daemon should be run and overseen by supervisor script.

Also see screenshots with how to setup Windows task: zip-file

 


Checklist 4: Sockets

Nice read is here. Thanks Gergely.

Also read here.

Dependencies:

  • socket.io
  • express (possibly)
  • node.js
way 1:
Note:
Use this way for development purposes, e.g. when you develop in Windows and you want to have it on constantly.
For production on Linux server use Supervisor.
This way will not react to any process dropped. Supervisor will reinstate such process.

Put inside of method schedule() of :

… this code:

Here is socket.js script:

Cron must be on for this to work.

way 2:

First we need Forever script.
It is somewhat like Supervisor, just for node scripts only:

Now again we use schedule, so cron must be up:

If you do not like Forever, but do not want to go for Supervisor, try PM2.

 

way 3:

Use Supervisor.
It will work on Linux server, not on Windows.
For windows, see above.

It is a script written in Python. It allows to control also other processes than node.js.
More here.

Sample Supervisor config might look like this (it should be placed at /etc/supervisor/conf.d/myapi.conf):

Checklist 5: config and .env

Make sure all settings in .env file are taken care of, like:

  • APP_DEBUG
  • APP_LOG_LEVEL
  • and the rest
Checklist 6: JS, CSS, NPM dependencies, SASS etc
Up to Laravel 5.3 … you need gulp
Laravel 5.4 – Laravel mix (webpack)

Run:

and

Also read this.

Laravel 5.4
.env constant

.env constant be set properly:

Dusk has different test directory.
Dusk does not come in a package and has to be installed
step 1: console composer

step 2: service provider

Register the provider within the register() method of your app\Providers\AppServiceProvider, like this:

install dusk

Next, run the dusk:install Artisan command:

More about Dusk – try Laravel docs and articles on this page.

Laravel 5.0 – 5.3

Up to Laravel 5.4 browser testing was done using Integrated Package.
Use link just above for detailed info.

Videos:

Laracast videos (Intermediate series: “2015-03-23-Intuitive Integration Testing“) are here:

  • video: Introduction and General Usage
  • video: Laravel and Integrated
  • video: Database Transactions
  • video: Example Workflow and Custom Methods
  • video: Selenium
  • video: Testing APIs
Installation:

More about installation etc. – here.

Usage Notes:
in windows you may do: vendor\bin\phpunit
note how slashes go!
command prompt expects backslash, not forward slash (like in most
tutorials done on Linux, or Apple, or VM (like HomeStead)