#[RPC\Cache]
Summary
Classname | Cache | |
Namespace | Ufo\RpcObject\RPC | |
Target | method | |
Arguments: | ||
$lifetimeSecond | type | int |
optional | true | |
default | 60 | |
$environments | type | array |
optional | true | |
default | ['prod'] |
Method Response Caching
By default, caching responses of your RPC methods is disabled, and each time you call the API, the method will be invoked.
However, sometimes, for certain methods whose results do not change often, it makes sense to enable response caching to increase request processing speed, save limits, reduce load on system components, etc.
The RPC Server uses the same CacheInterface implementation from Symfony that is used in your project. Therefore, there is no need for additional configuration.
Enabling caching is extremely simple; all you need to do is to add the attribute #[RPC\Cache] to a particular method.
2
3
4
5
6
7
8
9
10
namespace App\Api\Procedures;
use Ufo\RpcObject\RPC;
class SomeApiMethod implements IRpcService
{
#[RPC\Cache]
public function methodThatWorksForALongTime(): void {}
}
This setting will allow caching the response for one minute; subsequent requests to this method with the same parameters will receive the response instantly from the cache.
You can clear the cache as usual by executing the Symfony command:
If needed, you can increase the cache lifetime by passing the number of seconds in the parameter lifetimeSecond. For convenience, constants are created that cover most needs, but you can also pass the value as a simple number.
use Ufo\RpcObject\RPC\Cache;
Cache::T_MINUTE; // 60
Cache::T_5_MINUTES; // 300
Cache::T_10_MINUTES; // 600
Cache::T_30_MINUTES; // 1800
Cache::T_HOUR; // 3600
Cache::T_2_HOURS; // 7200
Cache::T_5_HOURS; // 18000
Cache::T_10_HOURS; // 36000
Cache::T_DAY; // 86400
Cache::T_2_DAYS; // 172800
Cache::T_3_DAYS; // 259200
Cache::T_5_DAYS; // 432000
Cache::T_10_DAYS; // 864000
Cache::T_WEEK; // 604800
Cache::T_2_WEEKS; // 1209600
Cache::T_3_WEEKS; // 1814400
Cache::T_MONTH; // 2592000
Cache::T_2_MONTHS; // 5184000
Cache::T_3_MONTHS; // 7776000
Cache::T_HALF_YEAR; // 15724800
Cache::T_YEAR; // 31536000
Also, you can change the environment settings on which caching can be enabled. By default, caching only works in the prod environment. However, you can change this by passing an array of environment names in which you want to cache results. In the example below, the result will be cached for one day for the prod and dev environments.
2
3
4
5
6
7
8
9
10
namespace App\Api\Procedures;
use Ufo\RpcObject\RPC;
class SomeApiMethod implements IRpcService
{
#[RPC\Cache(lifetimeSecond: RPC\Cache::T_DAY, environments: ['dev', 'prod'])]
public function methodThatWorksForALongTime(): void {}
}