sfneal/caching

Traits & interfaces for utilizing cache mechanisms to store frequently retrieved data.

4.1.0 2024-05-22 19:56 UTC

This package is auto-updated.

Last update: 2024-11-22 20:58:21 UTC


README

Packagist PHP support Latest Version on Packagist Build Status StyleCI Scrutinizer Code Quality Total Downloads

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.