In Rails, you can do:
articles = Rails.cache.fetch "blog-articles" do
BlogArticles.all
end
Therefore I created a simple class for my tiny PHP projects that will basically do the same. First of all, require the class:
<?php require_once 'cache.php';
And create a folder named tmp
. Note that you can change it by updating the CACHE_PATH
constant on the cache class.
Then, in a similar way you can do:
$articles = Cache::fetch("blog-articles", function() {
return mysql_query("select * from blog_articles;");
});
The return can be any kind of object, since it will be serialized using PHP's built-in functions.
A nice way to use it in a real app is the following:
$user_projects = Cache::fetch("user-projects-" . $user->updated_at, function() {
return mysql_query("select * from projects where user_id = $user->id;");
});
In the example above, anytime you will update the $user.updated_at
timestamp, the cache will be invalidated.