I am working on a Symfony2 project using Doctrine. I want to optimise the API performance by adding cache to queries.
I have looked at few options such as:
Not to sure with which one I should go but to me it seems like caching data at Doctrine level would be most suitable.
Saying that I would like someone to help me or guide me how to set up Doctrine cache and explain how it exactly works.
I.e I have this query:
class QueryFactory
protected $connect;
public function __construct(Connection $connection)
{
$this->connect = $connection;
}
private function myQuery()
{
return $this->connect->createQueryBuilder()
->select('user_id')
->from('users', 'u')
->where('u.user_id = 2');
}
}
How would I add a cache to this query? Is there any Doctrine library I need to inject any thing I need to use
?
In doctrine
to cache queries or results you can do the following:
private function myQuery()
{
return $this->connect->createQueryBuilder()
->select('user_id')
->from('users', 'u')
->where('u.user_id = 2')
->getQuery()
->useQueryCache(true) // here
->useResultCache(true); // and here
}
Check doc for more info about these methods. This will make your
cache driver working - doesn't matter what driver you are using.
To configure Symfony
to use specific query driver you need to adjust your settings in config.yml
- check this to see complete list of options. What is important in your cache is (this is apc
configuration example):
entity_managers:
some_em:
query_cache_driver: apc
metadata_cache_driver: apc
result_cache_driver: apc
You might also want to check this and this blog entries
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With