Download the PHP package directorytree/activeredis without Composer
On this page you can find all versions of the php package directorytree/activeredis. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download directorytree/activeredis
More information about directorytree/activeredis
Files in directorytree/activeredis
Package activeredis
Short Description An ActiveRecord implementation for Redis.
License MIT
Informations about the package activeredis
An Active Record implementation for Redis hashes in Laravel.
ActiveRedis provides you simple and efficient way to interact with Redis hashes using an Eloquent-like API.
Index
- Requirements
- Installation
- Usage
- Creating Models
- Model Identifiers
- Model Timestamps
- Model Casts
- Model Events
- Model Connection
- Updating Models
- Deleting Models
- Expiring Models
- Querying Models
- Chunking
- Searching
- Testing
- Credits
Requirements
- PHP >= 8.1
- Redis >= 3.0
- Laravel >= 9.0
Installation
You can install the package via composer:
Usage
Creating Models
To get started, define a new ActiveRedis model:
Then, create models with whatever data you'd like:
[!important] Without model casts defined, all values you assign to model attributes will be cast to strings, as that is their true storage type in Redis.
This will create a new Redis hash in below format:
For example:
Access attributes as you would expect on the model instance:
[!important] Before you begin using your model in production, consider possible searchable attributes that you may like to be part of your model schema, as these should not be modified once you have existing records.
Model Identifiers
When creating models, ActiveRedis will automatically generate a UUID for each model, assigned to the id
attribute:
You may provide your own ID if you'd prefer:
[!important] Redis keys are case-sensitive. Be mindful of this, as it impacts queries, discussed below.
Attempting to create a model with an ID that already exists will result in a DuplicateKeyException
:
Similarly, attempting to create a model with an empty ID will throw a InvalidKeyException
:
If you're running a high traffic application that may encounter a race condition, you may pass in true
in the second argument to create
to ignore the DuplicateKeyException
and delete the existing record:
Similarly, you may pass in true
into the save
method to ignore the exception and delete the existing record:
To change the name of the field in which the model key is stored, override the key
property:
ActiveRedis will always generate a new UUID in the key's attribute if you do not provide one.
To change this behaviour or generate your own unique keys, you may override the getNewKey()
method:
[!important] Do not generate keys with colons (:) or asterisks (*). They are reserved characters in Redis.
This also applies to values of searchable attributes.
Model Timestamps
Models will also maintain created_at
and updated_at
attributes:
[!important] Timestamp attributes will be returned as
Carbon
instances when accessed.
To only update a models updated_at
timestamp, you may call the touch()
method:
You may provide a timestamp attribute to touch as well:
To disable timestamps, you may override the timestamps
property and set it to false
:
If you need to customize the names of the columns used to store the timestamps, you may define CREATED_AT
and UPDATED_AT
constants on your model:
Model Casts
To cast model attributes to a specific type, you may define a casts
property on the model:
When you access the attribute, it will be cast to the specified type:
Here is a list of all supported casts:
json
date
real
array
float
string
object
double
integer
boolean
datetime
timestamp
collection
immutable_date
immutable_datetime
decimal:<precision>
Enum casts are also available:
Model Events
ActiveRedis models dispatch several events, allowing you to hook into the following moments in a model's lifecycle:
retrieved
, creating
, created
, updating
, updated
, saving
, saved
, deleting
, and deleted
.
You may register listeners for these methods inside your model's booted
method:
You may return
false
from an event listener on thecreating
,updating
, ordeleting
events to cancel the operation.
If you prefer, you may also create a model observer:
And register it using the observe
method:
Model Connection
By default, models will use the default Redis connection defined in your Laravel configuration.
It is recommended to define a separate connection for your ActiveRedis models in your config/database.php
file, as your default Redis connection will contain other data, such as jobs, cache, and sessions.
This will make queries more efficient, as it will only need to scan over the keys owned by your models:
To use this connection, you may override the connection
property on the model:
Updating Models
You may update models using the update()
method:
Or by setting model attributes and calling the save()
method:
Deleting Models
To delete models, use the delete()
method on the model instance:
Or, you may also delete models by their ID:
You may delete multiple models by providing an array of IDs:
Expiring Models
To expire models after a certain amount of time, use the setExpiry()
method:
After 5 minutes have elapsed, the model will be automatically deleted from Redis.
To retrieve a model's expiry time, use the getExpiry()
method:
[!important] The value returned will be a
Carbon
instance, ornull
if the model does not expire.
Querying Models
Querying models uses Redis' SCAN
command to iterate over all keys in the model's hash set.
For example, when the Visit model is queried, the pattern visits:id:*
is used:
To begin querying models, you may call the query()
method on the model:
This will iterate over all keys in the model's hash set and return a collection of models matching the pattern.
Missing model methods will be forwarded to the query builder, so you may call query methods dynamically on the model if you prefer.
Finding
To retrieve specific models, you may use the find
method:
If you would like to throw an exception when the model is not found, you may use the findOrFail
method:
Chunking
You may chunk query results using the chunk()
method:
[!important] Redis does not guarantee the exact number of records returned in each SCAN iteration. See https://redis.io/docs/latest/commands/scan/#the-count-option for more information.
Or call the each
method:
You may return false
in the callback to stop the chunking query:
Searching
Before attempting to search models, you must define which attributes you would like to be searchable on the model:
[!important] Consider searchable attributes to be part of your model schema. They should be defined before you begin using your model. Do not change these while you have existing records. Doing so will lead to models that cannot be retrieved without interacting with Redis manually.
When you define these attributes, they will be stored as a part of the hash key in the below format:
For example:
If you do not provide a value for a searchable attribute, literal string null
will be used as the value in the key:
When multiple searchable attributes are defined, they will be stored in alphabetical order from left to right in the hash key:
For example:
[!tip] Because searchable attributes should not be modified while you have existing records, you may find it useful name your models in a way that references the searchable attributes. For example
UserVisit
.
Once the searchable attributes have been defined, you may begin querying for them using the where()
method:
You may omit searchable attributes from the query and an asterisk will be inserted automatically:
You may also use asterisks in your where clauses to perform wildcard searches:
You may also use a string literal 'null'
as a search value to query for models where the attribute is null
:
Searchable attribute values may be updated at any time on models. If they have been changed, the existing model instance is deleted in Redis, and a new one is saved automatically:
Testing
To run your application tests without a real Redis server, you may swap the underlying repository to an array.
This will allow you to test with your models without needing to interact with Redis:
Otherwise, you will need to run your tests with a Redis server running, and flush your Redis database after each test:
Credits
This package is directly inspired from Laravel's Eloquent, and most features are direct ports to a Redis equivalent.
I am forever grateful for the work Taylor Otwell has produced.
If you can, support his work by purchasing a sponsorship, or one of his many Laravel based services.
All versions of activeredis with dependencies
illuminate/support Version ^9.0|^10.0|^11.0
illuminate/contracts Version ^9.0|^10.0|^11.0
illuminate/collections Version ^9.0|^10.0|^11.0