Skip to content

ActiveRecord

Viames Marino edited this page May 23, 2018 · 18 revisions

Pair connects to MySQL DBMS with an ORM based on Active Record pattern. It does not require the configuration of XML files. Objects retrieved from the DB are cast in both directions to the required type (int, bool, DateTime, float, csv).

In addition, each class inherited from ActiveRecord supports many convenient methods including those for managing the internal cache for saving data that saves queries.

The Pair base tables are InnoDB utf-8mb4.

Object constructor

The purpose of this class is to provide inheritance for the methods of the ActiveRecord paradigm, which involves coupling a class to a database table.

Creating an object that inherits from ActiveRecord using the PHP __construct() method can be done in two ways:

  1. using the key field in the table
  2. manually populating all the expected properties

Key field of the table

To construct an object using the table key, you can indicate three types of keys:

  1. integer for simple tables or autoincrement
  2. string for simple tables
  3. Array for tables with composite keys

A query to the database will retrieve the object identified by the key value and all the properties of the object bound to the table fields will be populated and converted accordingly (see automatic cast).

Example:

<?php

use Pair\ActiveRecord;

class Person extends ActiveRecord {

	/**
	 * Property that binds db field id.
	 * @var int
	 */
	protected $id;

	/**
	 * Property that binds db field name.
	 * @var string
	 */
	protected $name;

	/**
	 * Name of related db table.
	 * @var string
	 */
	const TABLE_NAME = 'persons';
		
	/**
	 * Name of primary key db field.
	 * @var array
	 */
	const TABLE_KEY = 'id';

	/**
	 * Method called by constructor just after having populated the object.
	 */
	protected function init() {

		$this->bindAsInteger('id');

	}

}

$id = 1;
$person = new Person($id);

print $person->name;

The $person object has the id and name properties populated as in the record of db where id = 1.

Note: id object property is casted to integer when its value is collected by database record.

Populate object properties

The second way to create an object is the manual population of its properties. This is useful when you have already loaded a list of complete rows of the table and want to create the related objects without further queries.

To construct an object in this way, it is sufficient to pass as a parameter an object of type PHP stdClass containing the same properties of the object to be created and its values.

If some properties are not of the same expected type, an automatic cast will be performed by the parent ActiveRecord class.

Clone this wiki locally