sfneal / caching
Traits & interfaces for utilizing cache mechanisms to store frequently retrieved data.
Installs: 88 316
Dependents: 6
Suggesters: 0
Security: 0
Stars: 1
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ^8.0|^8.1|^8.2|^8.3
- laravel/framework: ^8.75|^9.0|^10.0|^11.0
- sfneal/redis-helpers: ^1.4|^2.0|^3.0
Requires (Dev)
- josiasmontag/laravel-redis-mock: >=1.2.6
- orchestra/testbench: ^7.40|^8.0|9.0
- phpunit/phpunit: ^9.6|^10.0|^11.0
- scrutinizer/ocular: ^1.8
- sfneal/currency: ^2.0
README
Traits & interfaces for utilizing cache mechanisms to store frequently retrieved data in Laravel applications.
Installation
You can install the package via composer:
composer require sfneal/caching
Usage
1. Add caching to an eloquent query
During the first call to (new CountUnreadInquiriesQuery())->fetch(600)
in a fresh application instance
(or for the first time since flushing the cache) the output of the execute method will be stored in
the Redis cache for 5 minutes (600 seconds).
If another call to (new CountUnreadInquiriesQuery())->fetch(600)
is made within the next 5 minutes, the
previous output will be retrieved from the Redis cache, forgoing the need to execute a full query to the
database. In this example the time saved is minimal but time saving become increasingly significant as
the complexity of a query increases.
# Importing an example model that extends Sfneal/Models/AbstractModels use App\Models\Inquiry; # Import Cacheable trait that stores the output of the execute method in a Redis cache using the cacheKey method to set # the key. Any serializable output from execute can be stored, in this case we're simply storing an integer use Sfneal\Caching\Traits\Cacheable; # Importing AbstractQuery as we're building an Eloquent query cache use Sfneal\Queries\AbstractQuery; class CountUnreadInquiriesQuery extends AbstractQuery { use Cacheable; /** * Retrieve the number of unread Inquiries. * * @return int */ public function execute(): int { return Inquiry::query()->whereUnread()->count(); } /** * Retrieve the Queries cache key. * * @return string */ public function cacheKey(): string { # using AbstractModel::getTableName() to dynamically retrievethetable name to set the cache prefix return Inquiry::getTableName().':unread:count'; } }
Testing
composer test
Changelog
Please see CHANGELOG for more information what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email stephen.neal14@gmail.com instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.
PHP Package Boilerplate
This package was generated using the PHP Package Boilerplate.