phpEZ v0.4.0

CachableModel

Trait for models supporting instance caching by ID.

Implements a simple identity map pattern: once a model instance is loaded, subsequent queries for the same ID return the cached instance.

Models must implement find() method; this trait wraps it with caching.

Usage:

class User extends Model {
  use CachableModel;

  public static function find(string $id_or_val, string $field = 'id'): ?static {
    // your find implementation
  }
}

$user1 = User::findById(5);      // Hits database
$user2 = User::findById(5);      // Returns cached instance
$user3 = User::findById(5, false); // Skips cache, hits database
Tags
subpackage

db

Table of Contents

Properties

$cache  : array<int, static>
Instance cache indexed by ID.

Methods

find()  : static|null
Find a model instance by field value. Must be implemented by using class.
findById()  : static|null
Find a model by ID with optional caching.

Properties

$cache

Instance cache indexed by ID.

protected static array<int, static> $cache = []

Methods

find()

Find a model instance by field value. Must be implemented by using class.

public abstract static find(string $id_or_val[, string $field = 'id' ]) : static|null
Parameters
$id_or_val : string

The value to search for.

$field : string = 'id'

The field name to search on. Defaults to 'id'.

Return values
static|null

The model instance if found, null otherwise.

findById()

Find a model by ID with optional caching.

public static findById(int|null $id[, bool $cachable = true ]) : static|null
Parameters
$id : int|null

The ID to find. Returns null if ID is null.

$cachable : bool = true

Whether to use/populate the instance cache. Defaults to true.

Return values
static|null

The model instance if found, null otherwise.

On this page

Search results