2017 © Pedro Peláez
 

cakephp-plugin cakephp-keyvalue-pairs

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

image

jorisvaesen/cakephp-keyvalue-pairs

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

  • Monday, March 28, 2016
  • by jorisvaesen
  • Repository
  • 2 Watchers
  • 3 Stars
  • 47 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 1 Forks
  • 0 Open issues
  • 2 Versions
  • 0 % Grown

The README.md

CakePHP 3 Key Value Pairs

Build Status Coverage Status License Latest Stable Version, (*1)

Map key-value pairs between datasource and application., (*2)

Requirements

  • PHP 5.4+
  • CakePHP 3.x

Installation

Using composer

Run the following command, (*3)

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

or copy the json snippet for the latest version into your project’s composer.json:, (*4)

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

You need to enable the plugin, (*5)

bin/cake plugin load JorisVaesen/KeyValuePairs

or copy this line into your config/bootstrap.php file:, (*6)

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

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

Usage

Add behavior

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

Options

Key Default Description
fields.key 'key' Name of the key field
fields.value 'value' Name of the value field
scope false If you want to set extra conditions
preventDeletion false Prevent pairs from being deleted. true to disallow deletion, array to specify keys that should not be removed
allowedKeys false array of allowed keys or false to allow any
cache false Enable or disable caching
cacheConfig 'default' A custom cache config that should be used

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

  • 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.

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., (*8)

First we create a database table to store the key value pairs and insert the defaults., (*9)

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., (*10)

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., (*11)

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)., (*12)

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

The MIT License (MIT), (*13)

Copyright (c) 2016 Joris Vaesen, (*14)

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:, (*15)

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

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., (*17)

The Versions

28/03 2016

dev-master

9999999-dev https://github.com/jorisvaesen/cakephp-keyvalue-pairs

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

  Sources   Download

MIT

The Requires

 

The Development Requires

orm cakephp key-value pairs

28/03 2016

3.0.0

3.0.0.0 https://github.com/jorisvaesen/cakephp-keyvalue-pairs

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

  Sources   Download

MIT

The Requires

 

The Development Requires

orm cakephp key-value pairs