Consistent caching in Laravel
This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.
During the development of StudentVIP we discovered that different parts of the team were using the handy remember()
method on database queries and Eloquent models to cache the results for a certain period of time, but with completely different and inconsistent intervals. In order to bring these cache timeouts into line and to allow them to be mode configurable from a application level when required we decided to place standardised cache times in a config file. That way, when the site was expecting or under heavy load we could simply edit the config file and increase the caching site-wide.
In app/config/cache.php
we added the following:
Of course, you may want to change these values. Tiny is 5 minutes, short is 1 hour, medium is 12 hours and long is 24 hours. Now, there are two ways to access this config values throughout your application:
Facade
The first way is to use the facade. It's a Laravel facade so still perfectly easy to test, but up to you as to how you want to go.
Dependency injection
The second way, the way we do it, is by injecting the dependency into the controller that requires access to these configuration values.
Now, probably not the most foolproof way, but when we were in a total rush to get this thing out the front door it was an acceptable solution.