The Pairs library is a PHP tool designed to efficiently store and retrieve key-value pairs in a database. It provides a simple and flexible interface for managing data in a relational database. Below is a comprehensive guide on how to use the library.
This library was initially a part of User Synthetics project but was extracted to become a standalone project.
The Pairs class allows you to create a meta table that consists of key-value pairs. Each row in the table represents a unique combination of key and reference ID, allowing you to store and retrieve data in a flexible and efficient manner. The class also supports linking the meta table to a parent table using foreign keys for data integrity and consistency.
- Create a meta table with key-value pairs
- Link the meta table to a parent table using foreign keys
- Add or update reference data based on key and reference ID
- Retrieve reference data based on key and reference ID
- Remove reference data based on key and reference ID
- Retrieve all data associated with a specific reference ID or matching a given pattern
- Utilizes the sQuery library for efficient SQL query generation.
- PHP 8.1 or higher
- MySQLi extension
- sQuery library (required for efficient query generation)
composer require ucscode/pairs
use Ucscode\Pairs\Pairs;
// Include the necessary files and create a mysqli connection
$mysqli = new mysqli("host", "username", "password", "database");
// Initialize the Pairs class
$pairs = new Pairs($mysqli, 'tablename');
$pairs->set('car', 'toyota', 2);
This sets the key "car" with the value "toyota" for the reference (owner) 2.
$value = $pairs->get('car', 2);
This retrieves the value for the key "car" and reference 2.
$value = $pairs->get('car', 2, true);
This retrieves the unix timestamp representing when the initial value for the specified key and reference was added to the database.
$pairs->remove('car', 2);
This removes the key-value pair for the key "car" and reference 2.
$allPairs = $pairs->getSequence();
This retrieves all available data grouped by reference.
$pairsByReference = $pairs->getSequence(2);
This retrieves all data for reference 2.
$pairsByKeyPattern = $pairs->getSequence(2, 'user-%');
This retrieves all data for reference 2 whose key matches words starting from "user-"
$foreignConstraint = new ForeignConstraint('parentTableName');
$foreignConstraint->describePrimaryKeyUnsigned(true);
$foreignConstraint->describePrimaryKeyNullable(false);
$foreignConstraint->describePrimaryKeyColumnName('id');
$pairs->setForeignConstraint($foreignConstraint);
This sets up a foreign constraint
where "parentTableName
" becomes the parent table, and the pairs table becomes the child.
Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request on the GitHub repository.
This project is licensed under the MIT License. See the LICENSE file for more information.