PHPackages                             jorisvaesen/cakephp-keyvalue-pairs - 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. [Database &amp; ORM](/categories/database)
4. /
5. jorisvaesen/cakephp-keyvalue-pairs

ActiveCakephp-plugin[Database &amp; ORM](/categories/database)

jorisvaesen/cakephp-keyvalue-pairs
==================================

CakePHP plugin to handle key-value pairs to be mapped between datasource and application

3.0.0(10y ago)2741MITPHPPHP &gt;=5.5

Since Mar 28Pushed 10y ago2 watchersCompare

[ Source](https://github.com/jorisvaesen/cakephp-keyvalue-pairs)[ Packagist](https://packagist.org/packages/jorisvaesen/cakephp-keyvalue-pairs)[ Docs](https://github.com/jorisvaesen/cakephp-keyvalue-pairs)[ RSS](/packages/jorisvaesen-cakephp-keyvalue-pairs/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (4)Versions (2)Used By (0)

CakePHP 3 Key Value Pairs
=========================

[](#cakephp-3-key-value-pairs)

[![Build Status](https://camo.githubusercontent.com/3efa97b965446cc4110018688476c6e1342aeda2b2d328227202e3f3548f584e/68747470733a2f2f7472617669732d63692e6f72672f6a6f72697376616573656e2f63616b657068702d6b657976616c75652d70616972732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/jorisvaesen/cakephp-keyvalue-pairs)[![Coverage Status](https://camo.githubusercontent.com/e3d012588f03fccc58a129d6b4e4ba6d1a71342cda893800689078fcc17a00f0/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6a6f72697376616573656e2f63616b657068702d6b657976616c75652d70616972732f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/jorisvaesen/cakephp-keyvalue-pairs?branch=master)[![License](https://camo.githubusercontent.com/1ff5151ce23c6629ea114abd5442e56eb8d101a6268fb969a35e9d1a37744584/68747470733a2f2f706f7365722e707567782e6f72672f6a6f72697376616573656e2f63616b657068702d6b657976616c75652d70616972732f6c6963656e7365)](https://github.com/jorisvaesen/cakephp-keyvalue-pairs#license)[![Latest Stable Version](https://camo.githubusercontent.com/50ed1479a6af33c93cff56ece196486e4dd990ef2656cba042ab8c3c9ff5137b/68747470733a2f2f706f7365722e707567782e6f72672f6a6f72697376616573656e2f63616b657068702d6b657976616c75652d70616972732f762f737461626c65)](https://packagist.org/packages/jorisvaesen/cakephp-keyvalue-pairs)

Map key-value pairs between datasource and application.

Requirements
------------

[](#requirements)

- PHP 5.4+
- CakePHP 3.x

Installation
------------

[](#installation)

### Using composer

[](#using-composer)

Run the following command

```
composer require jorisvaesen/cakephp-keyvalue-pairs:"~3.0"

```

or copy the json snippet for the latest version into your project’s `composer.json`:

```
{
    "require": {
        "jorisvaesen/cakephp-keyvalue-pairs": "~3.0"
    }
}

```

You need to enable the plugin

```
bin/cake plugin load JorisVaesen/KeyValuePairs

```

or copy this line into your `config/bootstrap.php` file:

```
Plugin::load('JorisVaesen/KeyValuePairs');
```

If you are already using `Plugin::loadAll();`, then this is not necessary.

Usage
-----

[](#usage)

### Add behavior

[](#add-behavior)

```
$this->addBehavior('JorisVaesen/KeyValuePairs.KeyValuePairs', [
    // Here you can override the default options
]);
```

### Options

[](#options)

KeyDefaultDescriptionfields.key`'key'`Name of the key fieldfields.value`'value'`Name of the value fieldscope`false`If you want to set extra conditionspreventDeletion`false`Prevent pairs from being deleted. `true` to disallow deletion, `array` to specify keys that should not be removedallowedKeys`false``array` of allowed keys or `false` to allow anycache`false`Enable or disable cachingcacheConfig`'default'`A custom cache config that should be used### Available functions

[](#available-functions)

- `getPair($key, $asEntity = false)` get the value of `$key`. When `$asEntity` is set true, it returns the complete entity (useful when you want to make changes to it).
- `getPairs($keys, $requireAll = true, $asEntity = false)` returns an associative array with the keys and its values. When `$requireAll` is set true, the function returns false when not all keys could be found. When `$asEntity` is set true, it returns the complete entities (useful when you want to make changes to it).

### Tips

[](#tips)

- **Cache invalidation happens on afterSave and afterDelete callbacks, when you use `updateAll`, these callbacks don't get called. In this case you should invalidate the cache yourself.**
- Caching is advisable and its duration can be set to `+999 days` since the cached result gets invalidated automatically when a pair gets saved or removed.
- Caching automatically saves all the pairs in the database and extracts the specific values from it. If you want a cache file for each record, disable caching in this plugin and do the caching yourself or suggest the functionality by doing a pull request.
- This plugin is rather new so it can contain bugs. If you find any or want to suggest enhancements, please use the issue tracker [here](https://github.com/jorisvaesen/cakephp-keyvalue-pairs/issues).

Example
-------

[](#example)

Lets say you have an application where the user can create invoices which should get a prefix and number when created, but this user wants to manage these values for new invoices.

First we create a database table to store the key value pairs and insert the defaults.

```
CREATE TABLE `configs` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `key` varchar(255) NOT NULL,
    `value` VARCHAR(255) NOT NULL,
    `is_deleted` TINYINT(1) NOT NULL DEFAULT 0,
    `modified` datetime NOT NULL,
    PRIMARY KEY (`id`),
    INDEX `key_index` (`key`),
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

INSERT INTO `configs` (`key`, `value`, `is_deleted`) VALUES ('invoice_prefix', 'INV-', 0);
INSERT INTO `configs` (`key`, `value`, `is_deleted`) VALUES ('invoice_next_number', '2016001', 0);

```

We create a cache config that should be used by the plugin.

```
Cache::config('pairs', [
    'className' => 'File',
    'duration' => '+999 days',  // cache gets invalidated automatically when a pair is saved or removed
    'path' => CACHE,
    'prefix' => 'pairs_'
]);
```

Next we add the behavior to our table in `Model/Table/ConfigsTable.php`.

```
public function initialize(array $config)
{
    ...

    $this->addBehavior('JorisVaesen/KeyValuePairs.KeyValuePairs', [
        'fields' => [               //  We just leave this the default
            'key' => 'key',
            'value' => 'value'
        ],
        'cache' => true,            //  Enable caching
        'cacheConfig' => 'pairs',   //  Tell the plugin to use the pairs cache config
        'scope' => [                //  Just as example to show how to use extra conditions when fetching pairs
            'is_deleted' => false
        ],
        'preventDeletion' => true,  //  Prevents us from deleting any record in this table (and thereby possibly break the app)
        'allowedKeys' => [          //  Prevents us from saving any other key than the ones specified here
            'invoice_prefix',
            'invoice_next_number'
        ]
    ]);
}
```

Now when a new invoice is created we can grab the values and increase the invoice number for new invoices (this automatically invalidates the cache).

```
public function add()
{
    ...

    $pairsTable = TableRegistry::get('Configs');
    // We set $requireAll and $asEntity to true to be sure all keys are there and we can make changes to it later
    $pairs = $pairsTable->getPairs(['invoice_prefix', 'invoice_postfix'], true, true);

    if (!$pairs) {
        // throw error
    }

    $invoice->number = $pairs['invoice_prefix']->value . $pairs['invoice_next_number']->value;

    if ($this->Invoices->save($invoice)) {
        $pairs['invoice_next_number']->value = (int)$pairs['invoice_next_number']->value + 1;
        $pairsTable->save($pairs['invoice_next_number']);
    }

    ...
}
```

License
-------

[](#license)

The MIT License (MIT)

Copyright (c) 2016 Joris Vaesen

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60% 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.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

3693d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/935b8cd6be3a6ff53cae55eead3916bcfabec5de937f75221bb37cecd7d92374?d=identicon)[jorisvaesen](/maintainers/jorisvaesen)

---

Top Contributors

[![jorisvaesen](https://avatars.githubusercontent.com/u/4093781?v=4)](https://github.com/jorisvaesen "jorisvaesen (3 commits)")[![lorenzo](https://avatars.githubusercontent.com/u/37621?v=4)](https://github.com/lorenzo "lorenzo (2 commits)")

---

Tags

ormcakephpkey-value pairs

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jorisvaesen-cakephp-keyvalue-pairs/health.svg)

```
[![Health](https://phpackages.com/badges/jorisvaesen-cakephp-keyvalue-pairs/health.svg)](https://phpackages.com/packages/jorisvaesen-cakephp-keyvalue-pairs)
```

###  Alternatives

[josegonzalez/cakephp-upload

CakePHP plugin to handle file uploading sans ridiculous automagic

5451.3M9](/packages/josegonzalez-cakephp-upload)[muffin/trash

Adds soft delete support to CakePHP ORM tables.

851.3M11](/packages/muffin-trash)[scienta/doctrine-json-functions

A set of extensions to Doctrine that add support for json query functions.

58523.9M35](/packages/scienta-doctrine-json-functions)[muffin/webservice

Simplistic webservices for CakePHP

88191.0k13](/packages/muffin-webservice)[admad/cakephp-sequence

Sequence plugin for CakePHP to maintain ordered list of records

46489.9k6](/packages/admad-cakephp-sequence)[riesenia/cakephp-duplicatable

CakePHP ORM plugin for duplicating entities (including related entities)

51384.5k4](/packages/riesenia-cakephp-duplicatable)

PHPackages © 2026

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