rodrigovr / php-aop-cache
Cache method calls using Aspect-Oriented Programming techniques.
dev-master
2021-09-06 23:08 UTC
Requires
- php: >=7.2.0
This package is not auto-updated.
Last update: 2025-07-08 20:56:46 UTC
README
Aspect-Oriented Caching of Method Calls Using Runkit7
Goals
This project allows you to decorate method calls with a caching behavior. In other words, this means that, without modifing the source code of a foreign class, you can "plug" a cache mechanism to a choosen public method.
When is it useful?
- Before refactoring large code bases.
- When dealing with third-party code.
- To avoid licensing issues.
- To avoid repeated code.
- To easily test caching backends.
This is not a complete list, just some insights!
Dependencies
- install and enable runkit7
- php 7.2+
What can be cached?
You must decorate only user defined methods. Native classes are not supported.
Ex: You cannot attach directly to PDO::query.
How to use?
-
install with composer:
composer require rodrigovr/php-aop-cache
-
as soon as possible, instantiate the Decorator with a given cache implementation:
use rodrigovr\Aop; ... $decorator = Cache\Decorator::create(new Cache\MemoryCache);
- attach the decorator to any methods you want to cache results:
$decorator->attachTo('SomeClass', 'methodName') ->attachTo('SomeClass', 'anotherMethodName') ->attachTo('AnotherClass', 'oneMoreMethod');
- if needed, set how long (in seconds), results will be cached
// cache results up to 5 minutes $decorator->expires(300);
- you can also limit cache entries by size (in bytes)
// results over 10MB will not be saved $decorator->limit(10000000);
- multiple decorators are supported
$applyMemoryCache = Cache\Decorator::create(new Cache\MemoryCache); $applySessionCache = Cache\Decorator::create(new Cache\SessionCache); $applyApcuCache = Cache\Decorator::create(new Cache\SessionCache);
- you can create custom caching backends
use rodrigovr\Aop; class MyCache implements Cache\Storage { public function save($key, $value, $ttl) { // your custom save implementation } public function load($key) { // custom load implementation } } $decorator = Cache\Decorator::create(new MyCache)->expires(120);