PHPackages                             kaingnx/reference-cache-trait - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. kaingnx/reference-cache-trait

ActivePlugin[Caching](/categories/caching)

kaingnx/reference-cache-trait
=============================

CakePHP Trait for caching commonly used reference data/entities.

00PHPCI failing

Since Oct 1Pushed 6y ago1 watchersCompare

[ Source](https://github.com/KainGNX/reference-cache-trait)[ Packagist](https://packagist.org/packages/kaingnx/reference-cache-trait)[ RSS](/packages/kaingnx-reference-cache-trait/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependenciesVersions (1)Used By (0)

Reference Cache Trait for CakePHP 3.x
=====================================

[](#reference-cache-trait-for-cakephp-3x)

This trait is intended for use with CakePHP entity classes in caching commonly used reference tables such as cities, states, zip codes, or countries. Using the trait requires a few steps and some basic configuration.

The intended usage for this trait of for entities which would otherwise have to repeatedly query data from reference tables, which is very slow due to adding extra queries for every entity created, and possibly be exponential.

This trait will cache entire reference tables based on the namespace of the entity using it, and then the name space of the entity being cached with a 'entities' array within.

The cache list will not be stored directly under its namespace to allow parallel properties to be stored within that namespace if needed in the future.

Usage
-----

[](#usage)

1. Add `use KainGNX\Model\Entity\Traits\ReferenceCacheTrait` to the top of the desired class.
2. Override the Entity contructor that will use this trait
3. After the parent constructor callback, call `$this->initReferenceCache([])` with a definition list passed in
4. Make sure the definition list follows the pattern for `$this->referenceDefinition`, see comments
5. To get a list of properties from the cached, call `$this->getCachedEntities('DefinitionKey')` in the entity where needed
6. Make sure the 'DefinitionKey' matches a property structured element within `$this->referenceDefinition`

The reason a `DefinitionKey` is needed is to support multiple cached lists per entity. This due to the fact that traits can not be extended and the entity that uses it will share the same instances of methods and properties.

Reference Cache Definition
--------------------------

[](#reference-cache-definition)

Must be defined the constructor of entity using this trait. Used to define the options for caching each table and its entities

#### Reference Cache Definition Example

[](#reference-cache-definition-example)

REQUIRED :: Use the following pattern for each element of `ReferenceCacheTrait::cacheDefinition` array. After overriding the constructor of your entity where this will be used, do something similar to the following example. Multiple items may be added.

```
    $this->initReferenceCache(
        'States' => [
            'tableRegistryAlias' => 'Cities',
            'entityNamespace' => 'App.Model.Entity.EntityName',
            'referenceProperty' => 'property_name',
            'keyField' => 'field_name_of_entity',
            'conditions' => []
        ]
    );
```

#### Adding Reference Definitions Afterwards

[](#adding-reference-definitions-afterwards)

Simply do the following, and it will be merged with existing definitions. Again, multiple items maybe added.

```
    $this->addReferenceDefinition(
        'MoreStates' => [
            'tableRegistryAlias' => 'MoreCities',
            'entityNamespace' => 'App.Model.Entity.EntityName',
            'referenceProperty' => 'property_name',
            'keyField' => 'field_name_of_entity',
            'conditions' => []
        ]
    );
```

##### Reference Cache Definition Properties

[](#reference-cache-definition-properties)

For sake of consistency and following the CakePHP convention, each cache definition should be keyed by the plural table name.

- `tableRegistryAlias`: CakePHP Table Alias of the Entity to cache
- `entityNamespace`: Array key used to store entities in cache under entity dotted namespace
- `referenceProperty`: The property of the entity used to pull from the cache, such as the foreign key, or field of choosing
- `keyField`: The field name value which return entites are keyed to
- `conditions`: Conditions on which to select the entities

Whichever entity is using a cache trait, the pathing to the cached sub entities will be the parent entity namespace with slashes replaced with dots, and then a child array using the namespace of the child entity with slashes replaced with dots.

The `entityNamespace` could be derived from an instance of a table object, it is better to passed it in directly so that a table does not have to be created for each entity even when cached to look up and convert that value.

To avoid cache conflicts, and maintiain context of `conditions` when cached, all entites will be cached in a dotted namespace reflecting the parent class of the reference cache.

##### Example from the root of the Cache

[](#example-from-the-root-of-the-cache)

`App.Model.Entity.ParentEntity' => 'App.Model.Entity.ChildEntity' => ['entities] => \App\Model\Entity\ChildEntity[]`

So for example States is the parent of Cities, and this would be the array path to the cached entities in the `\Cake\Cache\Cache`.

`App.Model.Entity.States => App.Model.Entity.Cities => entities`

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity0

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity36

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/3d48ff23d0d44060563bc1bfbdb0c1f3b6ac6305a2158273e5792bfba585c5df?d=identicon)[jhorvath](/maintainers/jhorvath)

---

Top Contributors

[![jason-horvath](https://avatars.githubusercontent.com/u/16722042?v=4)](https://github.com/jason-horvath "jason-horvath (6 commits)")

### Embed Badge

![Health badge](/badges/kaingnx-reference-cache-trait/health.svg)

```
[![Health](https://phpackages.com/badges/kaingnx-reference-cache-trait/health.svg)](https://phpackages.com/packages/kaingnx-reference-cache-trait)
```

###  Alternatives

[predis/predis

A flexible and feature-complete Redis/Valkey client for PHP.

7.8k305.7M2.4k](/packages/predis-predis)[snc/redis-bundle

A Redis bundle for Symfony

1.0k39.4M67](/packages/snc-redis-bundle)[react/cache

Async, Promise-based cache interface for ReactPHP

444112.4M40](/packages/react-cache)[wp-media/wp-rocket

Performance optimization plugin for WordPress

7431.3M3](/packages/wp-media-wp-rocket)[illuminate/cache

The Illuminate Cache package.

12835.6M1.4k](/packages/illuminate-cache)[colinmollenhour/php-redis-session-abstract

A Redis-based session handler with optimistic locking

6325.6M14](/packages/colinmollenhour-php-redis-session-abstract)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
