How To Activate Cache In Symfony – FilesystemAdapter Symfony

Even if cache documentation exists in symfony website, I have not been able to find a good tutorial for how to activate or implement symfony cache system. So, I tried several methods until succeeded to implement the cache.

Anyway I am sure there are other methods you can implement the filesystemadapter but I will show you how I implemented it in my application.

In controller function I initialized the cache adapter with the following code:

$cache = new FilesystemAdapter();

Now we have to check if our cached object is already made or not. So we will check this with the following command:

$cached_post = $cache->getItem('post_'.$post->getId());
    $cached = $cached_post ->get();
    if(is_array($cached )){
      return $this->render(
       		$url, $cached 
      	);
    }

 

Here I check if the post is already cached, if it is I will return the view with post from cache, if it's not the function will go on and will get the post from database. Before to send the post from databasse to view I update the cache with this post, so next time when I will run this function the code execution will stop at the above verification.

if(!$cached_post->isHit()){ 
      $cached_post->set($data); 
      $cache->save($cached_post);	
    }

With the above function check if my post already exist in the cache files, if it's not I will save my post there. This is the way I have implemented few cache functions. Anyway this is not all you need to do for cache, because now, if you update your post name or description (the excerpt) the changes will not be seen on the website because the post it isn't taken from database but from cache and the cache is not updated, when you update the database. In the next tutorial I will show you how to delete a cached object in symfony with filesystemadapter.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x