Zeta Components - high quality PHP components

eZ Components - PersistentObject

Introduction

The PersistentObject component provides object persistence for PHP 5 using a database. PersistentObject uses the Database component to provide database abstraction. It does not rely on code generation and does not force a specific inheritance structure to work.

PersistentObject is built to be fast and flexible, allowing you to build persistent classes in the same way as any other class in your application. It also utilizes the query abstraction layer of the Database component to make it easy to build queries. Please refer to the API documentation of ezcQuerySelect for detailed examples on how to use the query abstraction layer.

The PersistentObjectDatabaseSchemaTiein component allows you to automatically generate the definition files needed by PersistentObject from a database schema or the structure of your database. For more information, please refer to the API documentation on ezcPersistentObjectSchemaGenerator.

Class overview

ezcPersistentSession is the main API for interacting with the persistent objects. Loading, saving and deleting persistent objects is done through this class. ezcPersistentSessionIdentityDecorator can be used to add identity mapping support to it (see Identity mapping).

Basic usage

This chapter describes the typical usage of PersistentObject with a single persistent class, using MySQL as the persistence storage.

The persistent class

We want to make a simple class, representing a person, persistent using a persistent object. This is a simple class with only a few members:

  1. <?php
  2. class Person
  3. {
  4.     private $id null;
  5.     public $name null;
  6.     public $age null;
  7.     public function getState()
  8.     {
  9.         $result = array();
  10.         $result['id'] = $this->id;
  11.         $result['name'] = $this->name;
  12.         $result['age'] = $this->age;
  13.         return $result;
  14.     }
  15.     public function setState( array $properties )
  16.     {
  17.         foreach( $properties as $key => $value )
  18.         {
  19.             $this->$key $value;
  20.         }
  21.     }
  22. }
  23. ?>

The id member will map to the required persistent identifier. It has to default to null. This is not required for any of the other mapped members. The id field is a required unique identifier for this persistent object. It is generated by the identifier generator and usually maps to an auto increment column in the database.

For simplicity, we have made the name and age members of the Person class public. However, this is not required and in a real application you can use any access method you like. You can even make the data completely private.

All persistent objects must implement the getState() and setState() methods. They are used to retrieve the state of the object when saving it and to set it when loading it. The getState() method should always return the complete state of the object while the setState() method should set only one member at the time.

The state arrays used by getState() and setState() must be indexed by the property names, as defined in the persistence mapping below. They do not act on the database columns names.

The persistence mapping

We are going to map the Person class onto the following SQL table:

CREATE TABLE persons ( id integer unsigned not null auto_increment, full_name varchar(255), age integer, PRIMARY KEY (id) ) TYPE=InnoDB;

The fields map one to one to the members of the Person class. Using the InnoDB type is not required. We strongly recommend it however, since it supports transactions. The id column is of the type auto_increment. This is required for the id generator that we will use. Other id generators may have other requirements to work as expected.

In order for PersistentObject to be able to store objects of the Person class into the persons table, we need to tell it how the columns are mapped to class members. We will use ezcPersistentCodeManager to fetch the definitions when required.

ezcPersistentCodeManager requires us to define the mapping using the ezcPersistentObjectDefinition, ezcPersistentObjectIdProperty and ezcPersistentObjectProperty classes:

  1. <?php
  2. $def = new ezcPersistentObjectDefinition();
  3. $def->table "persons";
  4. $def->class "Person";
  5. $def->idProperty = new ezcPersistentObjectIdProperty;
  6. $def->idProperty->columnName 'id';
  7. $def->idProperty->propertyName 'id';
  8. $def->idProperty->generator = new ezcPersistentGeneratorDefinition'ezcPersistentNativeGenerator);
  9. $def->properties['name'] = new ezcPersistentObjectProperty;
  10. $def->properties['name']->columnName 'full_name';
  11. $def->properties['name']->propertyName 'name';
  12. $def->properties['name']->propertyType ezcPersistentObjectProperty::PHP_TYPE_STRING;
  13. $def->properties['age'] = new ezcPersistentObjectProperty;
  14. $def->properties['age']->columnName 'age';
  15. $def->properties['age']->propertyName 'age';
  16. $def->properties['age']->propertyType ezcPersistentObjectProperty::PHP_TYPE_INT;
  17. return $def;
  18. ?>

The first block of code creates the definition object and sets the database table and the name of the class to map. The second block defines the mapping of the identifier member and the algorithm that should be used to create identifiers for new objects. We will use ezcPersistentNativeGenerator, which simply retrieves the new id generated by auto_increment. If you rely on a database backend that does not support auto_increment (e.g. Oracle), ezcPersistentSequenceGenerator is the class to choose here.

The next two code blocks define the mapping between the database columns and the class members. It is possible to use the same name in the class and the database for a field.

The members must be inserted into the properties member, which is an associative array, using the name of the member as the key name. Note that this must not necessarily be the same name as the database column the property corresponds to. It is required that you use the property name here!

If you look at the API for ezcPersistentObjectDefinition, it also has a property named "columns" that is the same array as the "properties", except that it is mapped to the column names instead of the property names. This reverse mapping is set up by ezcPersistentCodeManager automatically.

Finally, we return the complete definition. Your definition will not work unless you return it to the manager.

To make the definition work with the ezcPersistentCodeManager, it must be put in a separate PHP file and given the name of the class in lowercase letters. In our example, the filename should be person.php.

For classes in namespaces (PHP 5.3 and newer), sub-directories are used for the namespaces. That means, the persistence definition for a class \My\Namespace\Person must reside in the file my/namespace/person.php.

The session object

The session object is in charge of the actual loading and saving of persistent objects. A session can be created by simply instantiating it:

  1. <?php
  2. $db ezcDbFactory::create'mysql://user:password@host/database' );
  3. $session = new ezcPersistentSession(
  4.     $db,
  5.     new ezcPersistentCacheManager( new ezcPersistentCodeManager"path/to/definitions" ) )
  6. );
  7. ?>

The session takes two arguments: a pointer to the database instance to use and the manager from which to retrieve persistent object definitions. You can also use a Database instance by using the ezcDbInstance class. You can then simply use ezcDbInstance::get(); instead of passing $db as argument to the ezcPersistentSession's constructor.

We are using ezcPersistentCodeManager to load the definitions directly from file. You should point it to the location where you saved the person.php file. If you have several directories containing definitions, you can use the ezcPersistentMultiManager class to add as many as you like. In addition to the code manager we use a cache manager. The cache manager makes sure the definition is loaded from disk only once.

While it is possible to create a new session each time you want to manipulate a persistent object, you will probably want to use the same session each time. This functionality can be achieved by using the ezcPersistentSessionInstance class:

  1. <?php
  2. $session = new ezcPersistentSessionezcDbInstance::get(),
  3.                                      new ezcPersistentCacheManager( new ezcPersistentCodeManager( ... ) ) );
  4. ezcPersistentSessionInstance::set$session ); // set default session
  5. // retrieve the session
  6. $session ezcPersistentSessionInstance::get();
  7. ?>

Lazy initialization

Lazy initialization is a mechanism to load and configure a component, only when it is really used in your application. This mechanism saves time for parsing the classes and configuration, when the component is not used at all during one request. You can find a description how you can use it for your own components and how it works in the ezcBase tutorial. The keyword for the database component is ezcInitPersistentSessionInstance.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. class customLazyPersistentSessionConfiguration implements ezcBaseConfigurationInitializer
  4. {
  5.     public static function configureObject$instance )
  6.     {
  7.         switch ( $instance )
  8.         {
  9.             case null// Default instance
  10.                 $session = new ezcPersistentSession(
  11.                     ezcDbInstance::get(),
  12.                     new ezcPersistentCodeManager'../persistent' )
  13.                 );
  14.                 return $session;
  15.             case 'second':
  16.                 $session = new ezcPersistentSession(
  17.                     ezcDbInstance::get(),
  18.                     new ezcPersistentCodeManager'../additionalPersistent' )
  19.                 );
  20.                 return $session;
  21.         }
  22.     }
  23. }
  24. ezcBaseInit::setCallback
  25.     'ezcInitPersistentSessionInstance'
  26.     'customLazyPersistentSessionConfiguration'
  27. );
  28. // Create and configure default persistent session
  29. $db ezcPersistentSessionInstance::get();
  30. // Create and configure additional persistent session
  31. $sb ezcPersistentSessionInstance::get'second' );
  32. ?>

ezcBaseInit::setCallback accepts as a first parameter a component specific key, which lets the component later request the right configuration callback. The second parameter is the name of the class to perform the static callback on. This class must implement the ezcBaseConfigurationInitializer class. Each component's lazy initialization calls the static method configureObject() on the referenced class.

This example shows a way to configure multiple database handlers, only when they are really requested in your application. The example does basically the same like the first example in this tutorial, but creates the connection not before it is really required.

In line 32 the default persistent session is first requested in this example, which does not exist yet, so that the configuration class earlier referenced through the setCallback() call will be asked for a new instance for the current instance name, which is 'null' for the default instance.

In the configureObject() method in line 8 we switch on the instance name and create and return the right newly created database handler. Line 35 shows, that this will also work with multiple database instances, creating an additional persistent session that reads the definition files from another directory (additionalPersistent).

Creating and updating an object

Creating a new Person object and making it persistent is straightforward:

  1. <?php
  2. $object = new Person();
  3. $object->name "Guybrush Threepwood";
  4. $object->age 31;
  5. $session->save$object );
  6. ?>

This code saves our newly created object to the database and generates an id for it. The id is set to the id property of the object. Since Guybrush is our first person, he is assigned the id of 1.

Of course, the age of Guybrush Threepwood is the source of much debate, and he is probably younger than 31. To change his age, simply edit the object and tell the session to update it.

  1. <?php
  2. $object->age 25;
  3. $session->update$object );
  4. ?>

Note that we used update() to store the object this time. This is because we want to trigger an UPDATE query instead of an INSERT query.

Finding objects

There are several ways to retrieve persistent objects from the database. The simplest is to fetch one object by its identifier.

  1. <?php
  2. $object $session->load'Person');
  3. ?>

This code retrieves the Guybrush object created above.

If you have stored a lot of persistent objects to the database and want to retrieve a list, you can use the find() method. The find() method requires a query parameter that can first be retrieved from the session.

  1. <?php
  2. $q $session->createFindQuery'Person' );
  3. $q->where$q->expr->gt'age'$q->bindValue15 ) ) )
  4.    ->orderBy'full_name' )
  5.    ->limit10 );
  6. $objects $session->find$q'Person' );
  7. ?>

This code will fetch a maximum of 10 Person objects where the age is higher than 15, sorted by name.

This is achieved by manipulating the query object returned by ezcPersistentSession->createFindQuery(). To learn more about query abstraction and how to use it, please refer to the specific subsection of the Database components tutorial.

The find() method will fetch the complete result set and instantiate it for you. This is not desirable if you are fetching large numbers of objects and you want it to be fast and efficient. For this you can use the findIterator() method:

  1. <?php
  2. $q $session->createFindQuery'Person' );
  3. $q->where$q->expr->gt'age'$q->bindValue15 ) ) )
  4.   ->orderBy'name' )
  5.   ->limit10 );
  6. $objects $session->findIterator$q'Person' );
  7. foreach( $objects as $object )
  8. {
  9.     // ...
  10. }
  11. ?>

This code will produce the same result as the first find() example. However, only one object will be instantiated and the data will be transferred from the database only when it is needed.

The final example uses a find query with a logical and to find objects:

  1. <?php
  2. $q $session->createFindQuery'Person' );
  3. $q->where(
  4.     $q->expr->lAnd(
  5.        $q->expr->eq'name'$q->bindValue'Guybrush Threepwood' ) ),
  6.        $q->expr->eq'age'$q->bindValue25 ) )
  7.     )
  8. );
  9. $objects $session->findIterator$q'Person' );
  10. foreach( $objects as $object )
  11. {
  12.     // ...
  13. }
  14. ?>

Deleting objects

The easiest way to delete persistent objects is to use the delete() method on the session:

  1. <?php
  2. $object $session->load'Person');
  3. $session->delete$object );
  4. ?>

Of course, you can only delete instantiated objects this way. If you want to delete an object or a whole series of objects that are not instantiated, you can use the deleteFromQuery() method:

  1. <?php
  2. $q $session->createDeleteQuery'Person' );
  3. $q->where$q->expr->gt'age'$q->bindValue15 ) ) );
  4. $session->deleteFromQuery$q );
  5. ?>

The above code will remove all persons from the database who are more than 15 years old.

Identifier generation

All persistent objects must have an identifier field. The identifier generation algorithm defines how the system will generate ids for new objects. This chapter describes the available generators.

ezcPersistentSequenceGenerator

The sequence generator relies on the PDO::lastInsertId() method to retrieve the ids for newly created persistent objects.

For databases supporting auto_increment (like MySQL and SQLite), use ezcPersistentNativeGenerator. Other databases must use a sequence. For example, the PostgreSQL person table definition should be as follows:

CREATE TABLE persons ( id integer unsigned not null, full_name varchar(255), age integer, PRIMARY KEY (id) ); CREATE SEQUENCE person_seq START 1;

If your database requires you to use a sequence, this parameter should be provided to ezcPersistentSequenceGenerator in the mapping definition.

  1. <?php
  2. $def->idProperty->generator = new ezcPersistentGeneratorDefinition(
  3.     'ezcPersistentSequenceGenerator',
  4.     array( 'sequence' => 'person_sequence' )
  5. );
  6. ?>

ezcPersistentNativeGenerator

The native generator relies on auto_increment, which is supported by, among others, MySQL and SQLite. An example table definition looks like this:

CREATE TABLE persons ( id integer unsigned not null auto_increment, full_name varchar(255), age integer, PRIMARY KEY (id) );

The corresponding generator definition is below:

  1. <?php
  2. $def->idProperty->generator = new ezcPersistentGeneratorDefinition(
  3.     'ezcPersistentNativeGenerator'
  4. );
  5. ?>

ezcPersistentManualGenerator

If you do not rely on a database mechanism to generate values for a primary key column, you have to use the ezcPersistentManualGenerator class. You can then set the value of the id property by hand and save the object afterwards.

For example:

CREATE TABLE persons ( login varchar(25), full_name varchar(255), age integer, PRIMARY KEY (login) );

In this table, the string value is used as the primary key. Therefore, we have to generate id values manually. Use the following definition:

  1. <?php
  2. $def->idProperty->generator = new ezcPersistentGeneratorDefinition(
  3.     'ezcPersistentManualGenerator'
  4. );
  5. ?>

For saving a new instance, use the following code:

  1. <?php
  2. $object = new Person();
  3. // Manually set the id
  4. $object->login "guybrush";
  5. $object->name "Guybrush Threepwood";
  6. $object->age 31;
  7. $session->save$object );
  8. ?>

Definition loaders

The session object needs to be able to fetch the persistent object definitions in order to function properly. The task of fetching the definitions is performed by a definition loader, which is provided to the session when it is instantiated.

ezcPersistentCodeManager

This is currently the only manager available. It simply reads the definition from a file with the same name as the class from the specified directory. It does not perform any error checking on the definition and simply assumes that it is correct.

Extending the definition loader

It is very easy to create your own definition loader. Simply extend the ezcPersistentDefinitionManager abstract class and implement the fetchDefinition() method:

  1. <?php
  2. class ezcPersistentCodeManager extends ezcPersistentDefinitionManager
  3. {
  4.     public function fetchDefinition$class )
  5.     {
  6.     }
  7. }
  8. ?>

The fetchDefinition() method should create the definition structure for the requested class or throw an exception.

Relations

Relations are defined within the persistence mapping.

Relation class overview

The following definition classes are available to realize object relations:

ezcPersistentOneToManyRelation
This class is used to define 1:n relations. For example, one person might be related to multiple addresses, but one address might only be related to one person.
ezcPersistentManyToManyRelation
Using this class, you can define n:m relations. For example, a person can be related to multiple addresses, while an address can be related to multiple persons.
ezcPersistentOneToOneRelation
With this class you can define 1:1 relations, which might be useful for slight de-normalization. For example, you can split your user data from the user credentials.
ezcPersistentManyToOneRelation
This relation (n:1) does not make sense on its own, but as the reverse connection for a 1:n relation.
ezcPersistentRelationCollection
This class allows you to define multiple relations to the same PHP class.

All of these classes extend the abstract class ezcPersistentRelation.

Relations basics

For the examples in this section, we will reuse the Person class, defined in The persistent class. In addition, we will use an Address class, which looks as follows:

  1. <?php
  2. class Address
  3. {
  4.     public $id null;
  5.     public $street null;
  6.     public $zip null;
  7.     public $city null;
  8.     public function setState( array $state )
  9.     {
  10.         foreach ( $state as $key => $value )
  11.         {
  12.             $this->$key $value;
  13.         }
  14.     }
  15.     public function getState()
  16.     {
  17.         return array(
  18.             "id" => $this->id,
  19.             "street" => $this->street,
  20.             "zip" => $this->zip,
  21.             "city" => $this->city,
  22.         );
  23.     }
  24. }
  25. ?>

The Address class will be extended later on to include relations. The following basic persistence mapping is used and extended for each example:

  1. <?php
  2. $def = new ezcPersistentObjectDefinition();
  3. $def->table "addresses";
  4. $def->class "Address";
  5. $def->idProperty                = new ezcPersistentObjectIdProperty;
  6. $def->idProperty->columnName    'id';
  7. $def->idProperty->propertyName  'id';
  8. $def->idProperty->generator     = new ezcPersistentGeneratorDefinition'ezcPersistentSequenceGenerator);
  9. $def->properties['street']                 = new ezcPersistentObjectProperty;
  10. $def->properties['street']->columnName     'street';
  11. $def->properties['street']->propertyName   'street';
  12. $def->properties['street']->propertyType   ezcPersistentObjectProperty::PHP_TYPE_STRING;
  13. $def->properties['zip']                 = new ezcPersistentObjectProperty;
  14. $def->properties['zip']->columnName     'zip';
  15. $def->properties['zip']->propertyName   'zip';
  16. $def->properties['zip']->propertyType   ezcPersistentObjectProperty::PHP_TYPE_STRING;
  17. $def->properties['city']                 = new ezcPersistentObjectProperty;
  18. $def->properties['city']->columnName     'city';
  19. $def->properties['city']->propertyName   'city';
  20. $def->properties['city']->propertyType   ezcPersistentObjectProperty::PHP_TYPE_STRING;
  21. return $def;
  22. ?>

Defining a simple relation

The following extensions are necessary for the given class and persistence mapping, to realize a simple 1:n relation. Each person will be able to have multiple addresses, but one address may only refer to one person.

The Address class needs to be enhanced as follows, to store the id of the Person it is related to.

  1. <?php
  2. class Address
  3. {
  4.     // ...
  5.     private $person;
  6.     // ...
  7.     public function getState()
  8.     {
  9.         return array(
  10.             // ...
  11.             "person"    => $this->person,
  12.         );
  13.     }
  14. }
  15. ?>

Additionally, we need to define the new property $person in the persistence mapping of the Address class:

  1. <?php
  2. // ...
  3. $def->properties['person'] = new ezcPersistentObjectProperty;
  4. $def->properties['person']->columnName   'person_id';
  5. $def->properties['person']->propertyName 'person';
  6. $def->properties['person']->propertyType ezcPersistentObjectProperty::PHP_TYPE_INT;
  7. ?>

The relation definition takes place in the persistence mapping of the Person class in The persistent class. It needs to be extended as follows:

  1. <?php
  2. // ...
  3. $def->relations["Address"] = new ezcPersistentOneToManyRelation(
  4.     "persons",
  5.     "addresses"
  6. );
  7. $def->relations["Address"]->columnMap = array(
  8.     new ezcPersistentSingleTableMap(
  9.         "id",
  10.         "person_id"
  11.     )
  12. );
  13. // ..
  14. ?>

A relation to another persistent object is defined in the property ezcPersistentObjectDefinition $relations, which is an array. Each relation must have the name of the persistent object class it refers to as the key in this array. An instance of one of the classes shown in Class overview must be the value. In this case, it is ezcPersistentOneToManyRelation. The parameter to its constructor are the names of the tables that the relation refers to. The first table is the table of the current object, and the second one refers to the related object.

To define which properties are used to realize the relation mapping, the property ezcPersistentOneToManyRelation->columnMap is used. It contains an array of (in this case) ezcPersistentSingleTableMap, which maps one column of each of the tables to one column of another. In the above case, the database column "id" from the table "persons" would be mapped to the column "person_id" in the table "addresses". In general, this means, that "id" is the primary key from the "persons" table and "person_id" is the foreign key in the "addresses" table, that refers to the "persons" table. Please note that the relation mappings are done on the table name/column name and not on the class name/property name.

If you want to map using several columns, you can add more ezcPersistentSingleTableMap instances to the columnMap array. For example, if you are using a person's first and last name as the primary key for the "persons" table, you could define the relation like this:

  1. <?php
  2. // ...
  3. $def->relations["Address"] = new ezcPersistentOneToManyRelation(
  4.     "persons",
  5.     "addresses"
  6. );
  7. $def->relations["Address"]->columnMap = array(
  8.     new ezcPersistentSingleTableMap(
  9.         "firstname",
  10.         "person_firstname"
  11.     ),
  12.     new ezcPersistentSingleTableMap(
  13.         "lastname",
  14.         "person_lastname"
  15.     )
  16. );
  17. return $def;
  18. ?>

Using a relation

To use the previously defined 1:n relation, ezcPersistentSession offers several new methods:

ezcPersistentSession->getRelatedObject()
This method can be used to retrieve a single related object to a given source object. If no related object can be found, it will throw an exception.
ezcPersistentSession->getRelatedObjects()
In contrast to ezcPersistentSession->getRelatedObject(), this method always returns an array of all related objects. It will not throw an exception if no related object can be found, but will instead return an empty array.
ezcPersistentSession->addRelatedObject()
Using this method, you can build a relation between two persistent objects. It will set the defined properties on the objects, but does not store them to the database automatically. (Exceptions are ezcPersistentManyToManyRelation objects. Further details are below.)
ezcPersistentSession->removeRelatedObject()
As the counterpart to ezcPersistentSession->addRelatedObject(), this method is used to remove the relation between two objects. It will not store the given objects for you, but only remove the necessary properties. (Again, exceptions are ezcPersistentManyToManyRelation objects. Further details are below.)

Using these methods, we can now retrieve all addresses that are related to one person:

  1. <?php
  2. $person $session->load"Person");
  3. $addresses $session->getRelatedObjects$person"Address" );
  4. ?>

The variable $addresses will then contain an array of all Address objects found for the Person object with an id of 1. To relate these addresses to another Person object, we can do the following:

  1. <?php
  2. $personOld $session->load"Person");
  3. $personNew $session->load"Person"23 );
  4. $addresses $session->getRelatedObjects$personOld"Address" );
  5. foreach ( $addresses as $address )
  6. {
  7.     $session->removeRelatedObject$personOld$address );
  8.     $session->addRelatedObject$personNew$address );
  9.     $session->update$address );
  10. }
  11. ?>

Defining n:m relations

The ezcPersistentManyToManyRelation class works slightly different than the other ezcPersistentRelation classes. For this kind of relation, you need an extra table in your database to store the relation records. The next example shows the definition of an ezcPersistentManyToManyRelation relation, based on the Person and Address example classes. Each person can have several addresses and each address can be used by several persons. You need to use the original example classes for this, thus we do not need to extend them here. The definition of the relational mapping for the Person class must be extended as follows:

  1. <?php
  2. // ...
  3. $def->relations["Address"] = new ezcPersistentManyToManyRelation(
  4.     "persons",
  5.     "addresses",
  6.     "persons_addresses"
  7. );
  8. $def->relations["Address"]->columnMap = array(
  9.     new ezcPersistentDoubleTableMap"id""person_id""address_id""id" )
  10. );
  11. return $def;
  12. ?>

In contrast to all other implementations of ezcPersistentRelation, the ezcPersistentManyToManyRelation constructor expects three table names:

A similar exception applies to columnMap of this relation definition. It consists of ezcPersistentDoubleTableMap instances, which carry four column names each. The first column is the column to choose from the source table (usually its primary key). The second column defines the column in your relation table that maps to the first column. In our example, the column "id" from the "persons" table maps to the column "person_id" from the relation table "persons_addresses". The same applies to the third and fourth columns. The third column defines the column of the relation table that maps to the fourth column given. The fourth column specifies the column of your destination table to use for mapping. In our example, the relation table "persons_addresses" has a column "address_id", which is a foreign key referring to the column "id" in the table "addresses".

As with ezcPersistentSingleTableMap instances, you can use multiple mappings in one ezcPersistentManyToManyRelation->columnMap array. Here, we use a person's first and last name for the mapping:

  1. <?php
  2. // ...
  3. $def->relations["Address"] = new ezcPersistentManyToManyRelation(
  4.     "persons",
  5.     "addresses",
  6.     "persons_addresses"
  7. );
  8. $def->relations["Address"]->columnMap = array(
  9.     new ezcPersistentDoubleTableMap"firstname""person_firstname""address_id""id" ),
  10.     new ezcPersistentDoubleTableMap"lastname""person_lastname""address_id""id" )
  11. );
  12. return $def;
  13. ?>

Using n:m relations

As stated earlier, the usage methods behave slightly differently when dealing with n:m relations. If you use ezcPersistentSession->addRelatedObject(), the desired relation record is inserted into the relation table. The same applies to the removeRelatedObject() method of ezcPersistentSession, which deletes the specific record. This also means that you do not need to store the affected objects explicitly after altering the relations between them. If you have made other changes to the objects, they must be stored to save the changes.

Aside from that, the ezcPersistentSession->delete() method keeps track of the relation records. If you delete a record, all of its relation records are automatically deleted.

Special 1:1 relations

If you want to use 1:1 relations, where two tables share a common primary key, you need to define a table to generate the key and the other table to use ezcPersistentManualGenerator. For our example, if one person may only have one address, the definition would be as follows:

  1. <?php
  2. $def = new ezcPersistentObjectDefinition();
  3. $def->table "addresses";
  4. $def->class "Address";
  5. $def->idProperty                = new ezcPersistentObjectIdProperty;
  6. $def->idProperty->columnName    'id';
  7. $def->idProperty->propertyName  'id';
  8. $def->idProperty->generator     = new ezcPersistentGeneratorDefinition'ezcPersistentManualGenerator);
  9. return $def;
  10. ?>

This is the relation (defined in the definition file of the Person):

  1. <?php
  2. // ...
  3. $def->relations["Address"] = new ezcPersistentOneToOneRelation(
  4.     "persons",
  5.     "addresses"
  6. );
  7. $def->relations["Address"]->columnMap = array(
  8.     new ezcPersistentSingleTableMap(
  9.         "id",
  10.         "person_id"
  11.     )
  12. );
  13. return $def;
  14. ?>

If you let both tables use ezcPersistentSequenceGenerator for the same key, ezcPersistentSession will fail to save a related object, since the id will already be set by the ezcPersistentSession::addRelatedObject() method.

Another way to make this work is to not use the same primary key for both tables, but to make the Address object have its own id and only use the Person id as a foreign key.

Reverse relations

Since you can always look at a relation from two sides, ezcPersistentRelation implementations can be configured to be "reverse". A reverse relation indicates that the relation is already defined in the opposite direction and that the original direction is the main used one. The one marked as "reverse" is a secondary one, for consistency reasons. For a relation that is marked as reverse, it is not possible to use ezcPersistentSession->addRelatedObject() and ezcPersistentSession->removeRelatedObject(). You can still use ezcPersistentSession->getRelatedObjects() for relations that are flagged "reverse".

For most relation types, the reverse attribute of the relation definition object is set to false by default. You can manually set it. Exceptions are ezcPersistentManyToOneRelation relations. This relation type only makes sense as a reverse relation for ezcPersistentOneToManyRelation. Therefore, the reverse attribute is set to true for ezcPersistentManyToOneRelation and is not publicly accessible for writing.

The following example shows the reverse relation definition for the n:m relations example:

  1. <?php
  2. // ...
  3. $def->relations["Person"] = new ezcPersistentManyToManyRelation(
  4.     "addresses",
  5.     "persons",
  6.     "persons_addresses"
  7. );
  8. $def->relations["Address"]->columnMap = array(
  9.     new ezcPersistentDoubleTableMap"id""address_id""person_id""id" ),
  10. );
  11. $def->relations["Address"]->reverse true;
  12. return $def;
  13. ?>

With the relation definition shown above, you would still be able to relate the Persons object to an Address object, but not to add or remove related Person objects to/from an Address. In other words, the following code still works:

  1. <?php
  2. $address $session->load"Address"23 );
  3. $persons $session->getRelatedObjects$address"Person" );
  4. // ...
  5. ?>

While the following would not work:

  1. <?php
  2. // ...
  3. foreach ( $persons as $person )
  4. {
  5.     $session->removeRelatedObject$address$person );
  6. }
  7. ?>

Instead, only the other direction works, because this one is the main direction.

  1. <?php
  2. // ...
  3. foreach ( $persons as $person )
  4. {
  5.     $session->removeRelatedObject$person$address );
  6. }
  7. ?>

Cascading deletes

Cascading relations are done through the flag "cascade" of a ezcPersistentRelation implementation. All implementations except the ezcPersistentManyToManyRelation class support this flag. It allows you to automatically delete all related objects for a source object when the source object is deleted.

The following example shows how to add a cascading relation to a relation definition, based on the example from Defining a simple relation:

  1. <?php
  2. // ...
  3. $def->relations["Address"] = new ezcPersistentOneToManyRelation(
  4.     "persons",
  5.     "addresses"
  6. );
  7. $def->relations["Address"]->columnMap = array(
  8.     new ezcPersistentSingleTableMap(
  9.         "id",
  10.         "person_id"
  11.     ),
  12. );
  13. $def->relations["Address"]->cascade true;
  14. return $def;
  15. ?>

If you now use the following, the Person object and all related Address objects are deleted:

  1. <?php
  2. $person $session->load"Person");
  3. $session->delete$person );
  4. ?>

Beware that this does not work with ezcPersistentManyToManyRelation instances, because it could cause serious inconsistencies in your data.

Defining multiple relations to the same PHP class

In some cases it might be necessary to define multiple relations to the same PHP class. An example for this can be seen when enhancing the Person example from The persistence mapping as follows:

CREATE TABLE persons ( id integer unsigned not null auto_increment, full_name varchar(255), age integer, mother integer, father integer, PRIMARY KEY (id) )

Here each person is connected to 2 objects of the same table: The mother and the father. Since only 1 PHP class per table is desired, the class needs to be referenced by the Person class twice.

Assuming that the 2 new properties of the Person class have been defined correctly in the persistence mapping, the following code can be used to achieve the desired relations:

  1. <?php
  2. // ... $def is the persistence defintion
  3. $relations = new ezcPersistentRelationCollection();
  4. // Mother relation
  5. $relations['mothers_children'] = new ezcPersistentOneToManyRelation(
  6.     'PO_person',
  7.     'PO_person'
  8. );
  9. $relations['mothers_children']->columnMap = array(
  10.     new ezcPersistentSingleTableMap'id''mother' )
  11. );
  12. $relations['mothers_children']->cascade true;
  13. $relations['mother'] = new ezcPersistentManyToOneRelation(
  14.     'PO_person',
  15.     'PO_person'
  16. );
  17. $relations['mother']->columnMap = array(
  18.     new ezcPersistentSingleTableMap'mother''id' )
  19. );
  20. // ..
  21. $def->relations['Person'] = $relations;
  22. ?>

2 relations need to be defined to reflect the relation between a mother an her children. "mother" defines the relation from a child to its mother and "mothers_children" defines the opposite direction, from a child to its mother. Both relations operate on the Person class itself, therefore an ezcPersistentRelationCollection is used to carry the relation definitions.

Relations are defined as shown earlier in this section. The only difference here is, that the relation definitions themselves are not added directly to the $relations property of the ezcPersistentObjectDefinition instance. Instead they are assigned to unique names on a relation collection, which is then added to the $relations property of the object definition.

The comment indicating further code (...) in the example above indicates that further relations are missing in the collection: The relations "father" and "fathers_children" are excluded here, since they work exactly like the corresponding mother relations, above. A fifth relation is shown below:

  1. <?php
  2. $relations = new ezcPersistentRelationCollection();
  3. // ... mother / father relations
  4. // Sibling relation
  5. $relations['siblings'] = new ezcPersistentManyToManyRelation(
  6.     "PO_person",
  7.     "PO_person",
  8.     "PO_sibling"
  9. );
  10. $relations['siblings']->columnMap = array(
  11.     new ezcPersistentDoubleTableMap"id""person""sibling""id" ),
  12. );
  13. $def->relations['MultiRelationTestPerson'] = $relations;
  14. // assigning the relation collection
  15. $def->relations['Person'] = $relations;
  16. ?>

As can be seen above, a relation collection can carry an arbitrary number of relations, which are of arbitrary type.

Using multiple relations to the same PHP class

To make use of the relations to the Person class defined in the last section, the name of the desired relation has to be submitted to all relation operations:

  1. <?php
  2. $mother   $this->session->load'Person');
  3. $children $this->session->getRelatedObjects(
  4.     $mother,
  5.     'Person',
  6.     'mothers_children'
  7. );
  8. ?>

The code above fetches all children of a mother, as defined by the relation "mothers_children". The third parameter to ezcPersistentSession->getRelatedObject() is mandatory in this case. If you leave it out, a ezcPersistentUndeterministicRelationException will be thrown. The parameter is ignored if you submit it when not working with a relation collection.

In the same manor a new related object can only be added if the affected relation is submitted to ezcPersistentSession->addRelatedObject() as shown below:

  1. <?php
  2. $newChild = new Person();
  3. $newChild->name "New child";
  4. $this->session->save$newChild );
  5. $this->session->addRelatedObject(
  6.     $mother,
  7.     $newChild,
  8.     'mothers_children'
  9. );
  10. // Make relation changes take effect
  11. $this->session->save$newChild );
  12. ?>

Identity mapping

The identity map pattern, as described by Martin Fowler, ensures that only 1 PHP object with the same identity exists. That means, if you load an object from the database a second time, the originally created instance is re-used instead of creating a new instance. In addition to that, identity mapping can potentially save SQL queries and therefore reduce database load.

Note that with identity mapping, the methods updateFromQuery() and deleteFromQuery() will result in a complete reset of the identity map. Further details on that can be found under Effects of identity mapping.

Activate identity mapping

Identity mapping is activated by wrapping an instance of ezcPersistentSessionIdentityDecorator around your existing ezcPersistentSession:

  1. <?php
  2. // $originalSession contains a valid ezcPersistentSession
  3. $identityMap = new ezcPersistentBasicIdentityMap(
  4.     $originalSession->definitionManager
  5. );
  6. $session = new ezcPersistentSessionIdentityDecorator(
  7.     $originalSession,
  8.     $identityMap
  9. );
  10. ?>

You can transparently exchange ezcPersistentSession and ezcPersistentSessionIdentityDecorator inside your application, since their APIs do not differ.

One point where you might experience problems are instanceof checks for ezcPersistentSession. Just replace these with checks for ezcPersistentSessionFoundation.

Effects of identity mapping

Identity mapping avoids that you have 2 different PHP objects with the same database identity in your application. For example:

  1. <?php
  2. // $identitySession is an ezcPersistentSessionIdentityDecorator
  3. $person $identitySession->load'Person'23 );
  4. // ... somewhere else in your app ...
  5. $samePerson $identitySession->load'Person'23 );
  6. ?>

The variables $person and $samePerson are both references to the very same object. In fact, the second call to $identitySession->load() does not issue a database query at all, but just returns the existing instance of the desired Person object, since this has already been loaded before.

Identity mapping also affects finding of persistent objects:

  1. <?php
  2. // $identitySession is an ezcPersistentSessionIdentityDecorator
  3. $person $identitySession->load'Person'23 );
  4. $person->name 'New Name';
  5. // ... somewhere else in your app ...
  6. $query $identitySession->createFindQuery'Person' );
  7. $persons $identitySession->find$query );
  8. ?>

The call to $identitySession->find() fetches all Person objects from the database. This includes the Person with ID 23, which has already been loaded before. Due to that, there is not a second instance of this object in $persons, but the existing instance is re-used. This does not save you an SQL query, but avoids inconsistencies. The change of the $name property of the Person object with ID 23 is reflected in the found objects, although the object has not been saved, yet.

Note: You should not use the methods updateFromQuery() and deleteFromQuery() with ezcPersistentSessionIdentityDecorator. If you use any of these methods, all cached objects will automatically be removed from the identity map, because the effects of these methods can not be traced by the mechanism. The reset of the identity map might result in unexpected inconsistencies, which should originally be avoided by the mechanism.

Related objects

Identity mapping also affects the loading of related objects:

  1. <?php
  2. // $identitySession is an ezcPersistentSessionIdentityDecorator
  3. $person $identitySession->load'Person'23 );
  4. $addresses $identitySession->getRelatedObjects(
  5.     $person,
  6.     'Address'
  7. );
  8. // ... somewhere else in your app ...
  9. $sameAddresses $identitySession->getRelatedObjects(
  10.     $person,
  11.     'Address'
  12. );
  13. ?>

The variable $sameAddresses contains the very same array of Address objects as $addresses. In fact, no second database call is issued, to fetch the related objects, since they have already been loaded before.

This also works, if you add or delete related objects:

  1. <?php
  2. // $identitySession is an ezcPersistentSessionIdentityDecorator
  3. $person $identitySession->load'Person'23 );
  4. $addresses $identitySession->getRelatedObjects(
  5.     $person,
  6.     'Address'
  7. );
  8. // Add a new address
  9. $newAddress = new Address();
  10. $identitySession->addRelatedObject(
  11.     $person,
  12.     $newAddress
  13. );
  14. // Remove an address
  15. $identitySession->removeRelatedObject(
  16.     $person,
  17.     $addresses[42]
  18. );
  19. // ... somewhere else in your app ...
  20. $sameAddresses $identitySession->getRelatedObjects(
  21.     $person,
  22.     'Address'
  23. );
  24. ?>

There is no additional database query performed on the second call to $identitySession->getRelatedObjects() here, too. Still, the $sameAddresses reflects the operations of adding a new Address to and removing the Address with ID 42 from the list of related objects. Even if these operations have not been reflected in the database, yet.

Pre-fetching of related objects

Using the identity map decorator allows you to pre-fetch related objects, using a JOIN. There are 2 different methods that ezcPersistentSessionIdentityDecorator has in addition to ezcPersistentSession. The first one allows you to load a certain object together with related objects:

  1. <?php
  2. // $identitySession is an ezcPersistentSessionIdentityDecorator
  3. $prefetchRelations = array(
  4.     'addresses' => new ezcPersistentRelationFindDefinition(
  5.         'Address',
  6.         null,
  7.         array(
  8.             'cities' => new ezcPersistentRelationFindDefinition(
  9.                 'City'
  10.             )
  11.         )
  12.     ),
  13.     'purchases' => new ezcPersistentRelationFindDefinition(
  14.         'Purchase'
  15.     )
  16. );
  17. $person $identitySession->loadWithRelatedObjects(
  18.     'Person',
  19.     23,
  20.     $prefetchRelations
  21. );
  22. // ... somewhere else in your app ...
  23. $addresses $identitySession->getRelatedObjects(
  24.     $person,
  25.     'Address'
  26. );
  27. foreach ( $addresses as $address )
  28. {
  29.     $city $identitySession->getRelatedObjects(
  30.         $address,
  31.         'City'
  32.     );
  33. }
  34. // ... somewhere else in your app ...
  35. $purchases $identitySession->getRelatedObjects(
  36.     $person,
  37.     'Purchase'
  38. );
  39. ?>

The method $idSession->loadWithRelatedObjects() allows you to load a certain object and its related objects (included nesting).

The array $prefetchRelations defines, which related objects are fetched. The first ezcPersistentRelationFindDefinition in the array instructs to load related objects of type Address. The second parameter to the constructor of ezcPersistentRelationFindDefinition can be used to specify the relation name, if you use multiple relations to the same PHP class. The third parameter is used to define deeper relations. In the example above, it defines that for each loaded Address object, the related object of class City is loaded.

The second element of the $prefetchRelations array defines that for the object to load, also all related objects of the Purchase class are loaded. This loading happens in a single SQL statement, using multiple JOIN statements.

After defining the relations to fetch, the Person with ID 23 is loaded, including the defined related objects. Therefore, none of the latter calls to $idSession->getRelatedObjects() results in a database query, since all of these related object sets have already been loaded in a single SQL query.

In a similar way, you can find a set of objects including their related objects. Assume that $prefetchRelations is defined in the same way as in the last example:

  1. <?php
  2. // $identitySession is an ezcPersistentSessionIdentityDecorator
  3. // $prefetchRelations = array( ... );
  4. $query $identitySession->createFindQueryWithRelations(
  5.     'Person',
  6.     $prefetchRelations
  7. );
  8. $persons $identitySession->find$query );
  9. // ... somewhere else in your app ...
  10. foreach ( $persons as $person )
  11. {
  12.     $addresses $identitySession->getRelatedObjects(
  13.         $person,
  14.         'Address'
  15.     );
  16.     foreach ( $addresses as $address )
  17.     {
  18.         $city $identitySession->getRelatedObjects(
  19.             $address,
  20.             'City'
  21.         );
  22.     }
  23.     $purchases $identitySession->getRelatedObjects(
  24.         $person,
  25.         'Purchase'
  26.     );
  27. }
  28. ?>

In this case, all Person objects are loaded from the database, including their related objects as defined. Therefore, none of the calls to $identitySession->getRelatedObjects() leads to a database query, but just returns the pre-fetched set of related objects.

Related object sub-sets

In many cases it is not desirable to load all objects of a certain class and their related objects. Therefore it is possible, to restrict the loaded objects, using the typical query manipulations. However, this might often mean, that the set of related objects fetched for an object does not contain all related objects of a type, but only a sub-set.

To work around this potential inconsistencies, the concept of named related object sub-sets was introduced:

  1. <?php
  2. // $identitySession is an ezcPersistentSessionIdentityDecorator
  3. $prefetchRelations = array(
  4.     'custom_addresses' => new ezcPersistentRelationFindDefinition(
  5.         'Address'
  6.     ),
  7. );
  8. $query $identitySession->createFindQueryWithRelations(
  9.     'Person',
  10.     $prefetchRelations
  11. );
  12. $query->where(
  13.     $query->expr->gte(
  14.         'custom_addresses_zip',
  15.         40000
  16.     ),
  17.     $query->expr->lte(
  18.         'custom_addresses_zip',
  19.         50000
  20.     ),
  21. );
  22. $persons $identitySession->find$query );
  23. // ... somewhere else in your app ...
  24. foreach ( $persons as $person )
  25. {
  26.     $addresses $identitySession->getRelatedObjectSubset(
  27.         $person,
  28.         'custom_addresses'
  29.     );
  30. }
  31. ?>

In this example the query to fetch Person objects and their related Address objects has been restricted by a WHERE clause: Only the persons of which the Address lies between ZIP code 40000 and 50000 are fetched and only these addresses are loaded as related objects. A person that has two addresses, one with ZIP code 42235 and the other with 12345, will be loaded with this query, but only one of its addresses is loaded. This is obviously not the full set of related objects of type Address for this person. Storing this set of Address objects in the identity map as usual would lead to inconsistencies.

Therefore, whenever you use a WHERE condition to restrict the set of loaded objects, a named related object sub-set is created. As can be seen in the example above, to fetch the pre-loaded Address objects for a Person, the method $identity->getRelatedObjectSubset() is used instead of getRelatedObjects(). This method receives the alias you have chosen before for a certain sub-set in the $prefetchRelations array. 'custom_addresses' is the array key used to define the pre-fetching of Address objects.

For this reasons, the array keys used in the $prefetchRelations array must be unique on all levels, if you want to restrict the pre-fetching query using a WHERE condition. As shown in the example above, the keys used to define related objects to be loaded, are also used, to access these specific relations in the query. 'custom_addresses_zip' is used to restrict on the property $zip of the Address objects to be fetched in the set custom_addresses.

Note: Normal sets of related objects and named sub-sets can exist beside each other in the identity map. Whenever you use addRelatedObject(), all named related objects sub-sets will be removed from the identity map, since the mechanism can not detect to which of these the object must be added and to which not. However, using removeRelatedObject() and delete() do not have this side-effect, and will simply be reflected in the named sets, too.

Creating named sub-sets of related objects also works with the createRelationFindQuery() method, which already exists in ezcPersistentSession. This method optionally receives a 4th parameter $setName on ezcPersistentSessionIdentityDecorator, to define the set to store related objects found:

  1. <?php
  2. // $identitySession is an ezcPersistentSessionIdentityDecorator
  3. $person $identitySession->load'Person'23 );
  4. $query $identitySession->createRelationFindQuery(
  5.     $person,
  6.     'Address',
  7.     null,
  8.     'custom_addresses'
  9. );
  10. $query->where(
  11.     $query->expr->gte(
  12.         'zip',
  13.         40000
  14.     ),
  15.     $query->expr->lte(
  16.         'zip',
  17.         50000
  18.     ),
  19. );
  20. $customAddresses $identitySession->find$query );
  21. // ... some where else in your app ...
  22. $sameCustomAddresses $identitySession->getRelatedObjectSubset(
  23.     $person,
  24.     'custom_addresses'
  25. );
  26. ?>

Retrieving the named sub-set of related objects works the same way before.

Note that there is no need to prefix the property names in the WHERE condition in this case. Since only one level of related objects can be loaded here, it is not necessary. Note also, that in this case, Address objects are only loaded for one specific Person and are not pre-fetched for any other Person object. Trying to access the created named related object sub-set for another Person will return null since these to do not exist.

You can also access the named related object sub-set just created, by using an equaling relation find query (which uses the same set name!). The identity mapping mechanism detects that you want to load this specific named set, determines that this is already loaded and simply returns it, instead of issuing another database query.