Cache stuff with almost no modification on your code:
<?php
use Computaria\Tardis;
use MyApp\Repository;
$apc = new Doctrine\Common\Cache\ApcCache;
$tardis = Tardis\Factory::grow($apc);
$slowRepository = new Repository\Country;
$fastRepository = $tardis->cacheCallsFrom($slowRepository);
$brazil = $fastRepository->findByCode('BR');
Requirements: PHP >= 5.5
What happened above:
$apc
is our cache storage.$tardis
is a factory of proxies, caching into$apc
.$tardis->cacheCallsFrom()
creates a new object which will cache and retrieve results from it.
Many:
- We can't cache final classes.
- We only cache public method calls.
- Methods which accept non-serializable arguments can't be cached auto-magically.
Will the cache-enabled object Tardis create be of the same instance from the original object?
Yes. The object created will be from a new class extending your original class.
Isn't creating a class on the fly expensive and slow?
Yes, although not as slow as you might think and it is only a once in a time operation.
How are you sure of what cache key to retrieve?
To create a cache key we use Full\Class\Name::methodName
and serialize
all its arguments, in order to have a unique identity to that call.
If a method, of the same class and with the same arguments, return different things you are in trouble.
How do I expire a cache entry?
You should use Doctrine\Cache, or your own cache storage configuration for that.
We are working on solutions for that. Have an idea? Help us!