eZ components - PersistentObject ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. contents:: Table of Contents Introduction ============ Persistent Object provides object persistence using a database for PHP 5. Persistent Object uses the Database components to provide database abstraction. It does not rely on code generation and does not force a specific inheritance structure to work. Persistent Object is built to be fast and flexible allowing you to build your persistent classes in the same way as any other class in your application. Class overview ============== This section gives you an overview of the main classes of Persistent Object. ezcPersistentSession ezcPersistentSession is the main API for interaction with the object persistence. Loading, saving and deleting persistent objects is done through this class. Basic Usage =========== This chapter describes typical usage of the Persistent Object package 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 persistent object. It is a simple class with only a few members: :: id; $result['name'] = $this->name; $result['age'] = $this->age; return $result; } public function setState( array $properties ) { foreach( $properties as $key => $value ) { $this->$key = $value; } } } ?> 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 e.g. access methods or properties or even having 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 be prepared to only set one member at the time. 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 Persistent Object 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 the ezcPersistentCodeManager to fetch the definitions when required. ezcPersistentCodeManager requires us to define the mapping using the ezcPersistentObjectDefinition, ezcPersistentObjectIdProperty and ezcPersistentObjectProperty classes: :: table = "persons"; $def->class = "Person"; $def->idProperty = new ezcPersistentObjectIdProperty; $def->idProperty->columnName = 'id'; $def->idProperty->propertyName = 'id'; $def->idProperty->generator = new ezcPersistentGeneratorDefinition( 'ezcPersistentSequenceGenerator' ); $def->properties['name'] = new ezcPersistentObjectProperty; $def->properties['name']->columnName = 'full_name'; $def->properties['name']->propertyName = 'name'; $def->properties['name']->propertyType = ezcPersistentObjectProperty::PHP_TYPE_STRING; $def->properties['age'] = new ezcPersistentObjectProperty; $def->properties['age']->columnName = 'age'; $def->properties['age']->propertyName = 'age'; $def->properties['age']->propertyType = ezcPersistentObjectProperty::PHP_TYPE_INT; return $def; ?> 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 the ezcPersistentSequenceGenerator which simply retrieves the new identifier generated by auto_increment. 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. If you look at the API of ezcPersistentObjectDefinition it also has a property named 'columns' which is the same array as the 'properties' except it is mapped on the column names instead of the property names. This reverse mapping is set up by the ezcPersistentCodeManager. 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 it should be put in a file named 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 simply by instantiating it: :: The session takes two arguments: a pointer to the database instance to use and the manager it should use to retrieve persistent object definitions. We are using the ezcPersistentCodeManager which loads 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 your definitions you can use the ezcPersistentMultiManager class to add as many as you like. 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: :: Creating and updating an object ------------------------------- Creating a new Person object and making it persistent is straight forward: :: name = "Guybrush Threepwood"; $object->age = 31; $session->save( $object ); ?> 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 will get the identifier 1. Of course, the age of Guybrush Threepwood is the source of much debate and most probably he is younger than 31. To make the change simply edit the object and tell the session to update it. :: age = 25; $session->update( $object ); ?> 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. :: load( 'Person', 1 ); ?> This code retrieves the Guybrush object created above. If you have stored a lot of persistent objects to the database and you want to retrieve a list you can use the find method. The find method requires a query parameter which you can retrieve from the session first. :: createFindQuery( 'Person' ); $q->where( $q->expr->gt( 'age', $q->bindValue( 15 ) ) ) ->orderBy( 'full_name' ) ->limit( 10 ); $objects = $session->find( $q, 'Person' ); ?> This code will fill fetch a maximum of 10 Person objects older than 15 years sorted by their names. 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 fetchIterator() method: :: createFindQuery( 'Person' ); $q->where( $q->expr->gt( 'age', $q->bindValue( 15 ) ) ) ->orderBy( 'name' ) ->limit( 10 ); $objects = $session->findIterator( $q, 'Person' ); foreach( $objects as $object ) { // ... } ?> This code will produce the same result as the first find() example. However, only one object will be instantiated and the data will be transfered from the database only when it is needed. Deleting objects ----------------- The easiest way to delete persistent objects is to use the delete method() on the session: :: load( 'Person', 1 ); $session->delete( $object ); ?> 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: :: createDeleteQuery( 'Person' ); $q->where( $q->expr->gt( 'age', $q->bindValue( 15 ) ) ); $session->deleteFromQuery( $q ); ?> When executed the above code will remove all persons older than 15 years old from the database. Identifier generation ===================== All persistent objects are required to 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. It is recommended to use auto_increment id columns for databases supporting it. This includes MySQL and SQLite. Other databases need to use a sequence. E.g for PostgreSQL the person table definition should look like: :: 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 the ezcPersistentSequenceGenerator in the mapping definition. :: idProperty->generator = new ezcPersistentGeneratorDefinition( 'ezcPersistentSequenceGenerator', array( 'sequence' => 'person_sequence' ) ); ?> 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 named the same 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: :: 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 1 person can be related to multiple addresses, while only 1 person can live at an address. ezcPersistentManyToManyRelation Using this class you can define n:m relations, for example a person can be related to multiple addresses, while multiple persons can live at one address. ezcPersistentOneToOneRelation With this class you can define 1:1 relations, which might be useful for slight de-normalization. For example, if you want to split your users 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. All of these classes extend the abstract class ezcPersistentRelation. Basics for the following examples --------------------------------- For the examples in this section, we will reuse the Person class, define in `The persistent class`_. In addition, we will use a class Address, which looks as follows:: $value ) { $this->$key = $value; } } public function getState() { return array( "id" => $this->id, "street" => $this->street, "zip" => $this->zip, "city" => $this->city, ); } } ?> The Address class will be extended later on to include the relation. The following basic persistence mapping is used and extended for each example:: table = "addresses"; $def->class = "Address"; $def->idProperty = new ezcPersistentObjectIdProperty; $def->idProperty->columnName = 'id'; $def->idProperty->propertyName = 'id'; $def->idProperty->generator = new ezcPersistentGeneratorDefinition( 'ezcPersistentSequenceGenerator' ); $def->properties['street'] = new ezcPersistentObjectProperty; $def->properties['street']->columnName = 'street'; $def->properties['street']->propertyName = 'street'; $def->properties['street']->propertyType = ezcPersistentObjectProperty::PHP_TYPE_STRING; $def->properties['zip'] = new ezcPersistentObjectProperty; $def->properties['zip']->columnName = 'zip'; $def->properties['zip']->propertyName = 'zip'; $def->properties['zip']->propertyType = ezcPersistentObjectProperty::PHP_TYPE_STRING; $def->properties['city'] = new ezcPersistentObjectProperty; $def->properties['city']->columnName = 'city'; $def->properties['city']->propertyName = 'city'; $def->properties['city']->propertyType = ezcPersistentObjectProperty::PHP_TYPE_STRING; ?> Defining a simple relation -------------------------- The following extensions are necessary to the given class and persistence mapping, to realize a simple 1:n relation. Each person will be able to have multiple addresses, but 1 address may only refer to 1 person. The Address class needs to be enhanced as follows, to store the id of the Person it is related to. :: $this->person, ); } } ?> Additionally, we need to define the new property $person in the persistence mapping of the Address class: :: properties['person'] = new ezcPersistentObjectProperty; $def->properties['person']->columnName = 'person_id'; $def->properties['person']->propertyName = 'person'; $def->properties['person']->propertyType = ezcPersistentObjectProperty::PHP_TYPE_INT; ?> The relation definition takes place in the persistence mapping of the Person class in `The persistent class`_. It needs to be extended as follows:: relations["Address"] = new ezcPersistentOneToManyRelation( "persons", "addresses" ); $def->relations["Address"]->columnMap = array( new ezcPersistentSingleTableMap( "id", "person_id" ), ); ?> 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, 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 the other one. If you want to map using several columns, you can add more ezcPersistentSingleTableMap instances to the columnMap array. 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 returns always an array of all related objects. It will not throw an exception if no related object can be found, but return an empty array. ezcPersistentSession->addRelatedObject() Using this method you can build a relation between 2 persistent objects. It will set the defined properties on the objects, but does not store those to the database automatically. (A little exception are ezcPersistentManyToManyRelation objects. Further details below.) ezcPersistentSession->removeRelatedObject() As the counterpart to ezcPersistentSession->addRelatedObject(), this method is used to remove the relation between 2 objects. It won't store the given objects for you, but only remove the necessary properties. (Again a little exception are ezcPersistentManyToManyRelation objects. Further details below.) Using these methods, we can now retrieve all addresses which are related to one person:: load( "Person", 1 ); $addresses = $session->getRelatedObjects( $person, "Address" ); ?> The variable $addresses will then contain an array of all Address objects found for the Person object with ID 1. To make this objects being related to another Person object, we can do the following:: load( "Person", 1 ); $personNew = $session->load( "Person", 23 ); $addresses = $session->getRelatedObjects( $personOld, "Address" ); foreach ( $addresses as $address ) { $session->removeRelatedObject( $personOld, $address ); $session->addRelatedObject( $personNew, $address ); $session->update( $address ); } ?> Defining n:m relations ---------------------- The eczPersistentManyToManyRelation class works in some parts 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 on basis of the Person and Address example classes. You need to use the original classes for this, hence we do not need to extend those here. The definition of the relational mapping for the Person class must be extended as follows:: relations["Address"] = new ezcPersistentManyToManyRelation( "persons", "addresses", "persons_addresses" ); $def->relations["Address"]->columnMap = array( new ezcPersistentDoubleTableMap( "id", "person_id", "address_id", "id" ), ); ?> In contrast to all other implementations of ezcPersistentRelation, the ezcPersistentManyToManyRelation constructor expects 3 table names: - The name of the current objects table. - The name of the related objects table. - The table name to store the relation records into. A similar exception applies to the columnMap of this relation definition: It consists of ezcPersistentDoubleTableMap instances, which carry 4 column names each. The first column is the column to choose from the source table. The second column maps the first one to a column of the relation table. Same applies to the 3rd and 4th column, which map the second column of the relation table to the desired column of the related objects table. As with ezcPersistentSingleTableMap instances, you can use multiple mappings in 1 ezcPersistentManyToManyRelation->columnMap array. Using n:m relations ------------------- As stated earlier, the n:m relations have also some exceptions in the usage methods. If you use ezcPersistentSession->addRelatedObject() the desired relation record is inserted into the relation table. 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 using one of the named methods. Beside that, the ezcPersistentSession->delete() method keeps track of the relation records. If you delete a record, all it's relation records are deleted automatically. Reverse relations ----------------- Since you can always look at a relation from 2 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 this direction is the mainly used one. For a relation that is marked as reverse, it is not possible to use ezcPersistentSession->addRelatedObject() and ezcPersistentSession->removeRelatedObject(). Generally the reverse attribute of relation definition objects is set to false per default, except for ezcPersistentManyToOneRelation relations. This relation type makes only sense as a reverse relation for ezcPersistentOneToManyRelations. Therefore the reverse attribute is set to false and not publicly accessible for writing. The following example shows the reverse relation definition for the last example:: relations["Person"] = new ezcPersistentManyToManyRelation( "addresses", "persons", "persons_addresses" ); $def->relations["Address"]->columnMap = array( new ezcPersistentDoubleTableMap( "id", "address_id", "person_id", "id" ), ); $def->relations["Address"]->reverse = true; ?> With the relation definition shown above, you would still be able to get the Person objects related to an Address object, but not to add or remove related Person objects to/from an Address. Cascading deletes ----------------- Cascading relations is done through the flag "cascade" of a ezcPersistentRelation implementation. All implementations, except the ezcPersistentManyToManyRelation class support this flag. It allows you to get all related objects for a source object automatically deleted, if the source object is deleted. The following example shows how to add cascading to a relation definition, based on the example from `Defining a simple relation`_:: relations["Address"] = new ezcPersistentOneToManyRelation( "persons", "addresses" ); $def->relations["Address"]->columnMap = array( new ezcPersistentSingleTableMap( "id", "person_id" ), ); $def->relations["Address"]->cascade = true; ?> If you now use :: load( "Person", 1 ); $session->delete( $person ); ?> The Person object and all related Address objects are deleted. Beware, that this does not work with ezcPersistentManyToManyRelation instances. .. Local Variables: mode: rst fill-column: 79 End: vim: et syn=rst tw=79