PersistentObject: ezcPersistentSessionIdentityDecorator
[ ]
[ ]
[ ]
[ ]
[ ]
Class: ezcPersistentSessionIdentityDecorator
|
This class decorates ezcPersistentSession with facilities of the identity map pattern. [
source]
Implemented Interfaces
An instance of this class is used to decorate an
ezcPersistentSession with the facilities of the identity map pattern (similar to {@see http://martinfowler.com/eaaCatalog/identityMap.html}).
The identity map pattern avoids inconsistencies in your application, by avoiding that the same database object exists in multiple different object instances. If your request the same object a second time, the already existing instance is returned instead of creating a new one. This can also save you some SQL queries and therefore database load, but this is not the primary target of the pattern.
You can now transparently replace $originalSession and $identitySession in most cases. Only the methods
updateFromQuery() and
deleteFromQuery() won't work properly, since the identity map cannot trace the changes produced by this method in the database. Attention: Calling these methods will result in a complete reset of the identity map!
Using the $options property, you can temporarely activate refetching of objects. Be careful with this option! While this is set to true, all object identities will be created from scratch and existing ones will be replaced. This is usually not desired! Use
refresh() to update object values from database instead.
Properties
Member Variables
Method Summary
|
public ezcPersistentSessionIdentityDecorator |
__construct(
$session, $identityMap, [$options = null] )
Creates a new identity map decorator. |
|
public void |
addRelatedObject(
$object, $relatedObject, [$relationName = null] )
Create a relation between $object and $relatedObject. |
|
public ezcQueryDelete |
createDeleteQuery(
$class )
Returns a delete query for the given persistent object $class. |
|
public ezcPersistentFindQuery |
createFindQuery(
$class )
Returns a select query for the given persistent object $class. |
|
public ezcPersistentFindWithRelationsQuery |
createFindQueryWithRelations(
$class, $relations )
Returns a select query for the given $class and its related objects as defined in $relations. |
|
public ezcPersistentRelationFindQuery |
createRelationFindQuery(
$object, $relatedClass, [$relationName = null], [$setName = null] )
Returns the base query for retrieving related objects. |
|
public ezcQuerySubSelect |
createSubQuery(
$parentQuery, $class )
Returns a sub-select for the given $class to be used with $parentQuery. |
|
public ezcQueryUpdate |
createUpdateQuery(
$class )
Returns an update query for the given persistent object $class. |
|
public void |
delete(
$object )
Deletes the persistent $object. |
|
public void |
deleteFromQuery(
$query )
Deletes persistent objects using the given $query. |
|
public array(object($class)) |
find(
$query, [$class = null] )
Returns the result of the $query as an array of objects. |
|
public ezcPersistentIdentityFindIterator |
findIterator(
$query, [$class = null] )
Returns the result of $query for the $class as an iterator. |
|
public array(string=>string) |
generateAliasMap(
$def, [$prefixTableName = true] )
Returns a hash map between property and column name for the given definition $def. |
|
public array(int=>string) |
getColumnsFromDefinition(
$def, [$prefixTableName = true] )
Returns all the columns defined in the persistent object. |
|
public object($relatedClass) |
getRelatedObject(
$object, $relatedClass, [$relationName = null] )
Returns the related object of a given $relatedClass for $object. |
|
public array(int=>object($relatedClass)) |
getRelatedObjects(
$object, $relatedClass, [$relationName = null] )
Returns the related objects of a given $relatedClass for $object. |
|
public array(ezcPersistentObject)|null |
getRelatedObjectSubset(
$object, $setName )
Returns the named related object subset with $setName for $object. |
|
public bool |
isRelated(
$sourceObject, $relatedObject, [$relationName = null], $sourceObj, $relatedObj )
Returns if $relatedObject is related to $sourceObject. |
|
public ezcPersistentObject |
load(
$class, $id )
Returns the persistent object of class $class with id $id. |
|
public ezcPersistentObject|null |
loadIfExists(
$class, $id )
Returns the persistent object of class $class with id $id or null. |
|
public void |
loadIntoObject(
$object, $id )
Loads the persistent object of $class with $id into the given $object. |
|
public ezcPersistentObject |
loadWithRelatedObjects(
$class, $id, $relations )
Loads an object of $class with $id and related objects defined by $relations. |
|
public void |
refresh(
$object )
Syncronizes the contents of $object with the database. |
|
public void |
removeRelatedObject(
$object, $relatedObject, [$relationName = null] )
Removes the relation between $object and $relatedObject. |
|
public void |
save(
$object )
Saves the new persistent object $object to the database using an INSERT INTO query. |
|
public void |
saveOrUpdate(
$object )
Saves or updates the persistent $object to the database. |
|
public void |
update(
$object )
Updates $object in the database using an UPDATE query. |
|
public void |
updateFromQuery(
$query )
Updates persistent objects using the query $query. |
Methods
__construct
Creates a new identity map decorator.
This identity map decorator wraps around $session and makes use of this to issue the actual database operations. Object identities are stored in the $identityMap. The $options influence the behavior of the identity session, like setting the $refetch option to force reloading of objects.
Parameters
addRelatedObject
Create a relation between $object and $relatedObject.
This method is used to create a relation between the given source $object and the desired $relatedObject. The related object is not stored in the database automatically, only the desired properties are set. An exception is {@ezcPersistentManyToManyRelation}s, where the relation record is stored automatically and there is no need to store $relatedObject explicitly after establishing the relation.
If there are multiple relations defined between the class of $object and $relatedObject (via ezcPersistentRelationCollection), the $relationName parameter becomes mandatory to determine, which exact relation should be used.
Newly added related objects are stored in the identity map and added to recorded relation sets. If not set of related object set is recorded, yet, the adding is ignored.
Parameters
Throws
| Class | Description |
ezcPersistentRelationNotFoundException |
if the deisred relation is not defined. |
ezcPersistentRelationOperationNotSupportedException |
if a relation to create is marked as "reverse" ezcPersistentRelation->reverse. |
createDeleteQuery
Returns a delete query for the given persistent object $class.
The query is initialized to delete from the correct table and it is only neccessary to set the where clause.
Attention: If you use a query generated by this method to delete objects, the internal
ezcPersistentIdentityMap will be completly reset. This is neccessary to avoid inconsistencies, because the session cannot trace which objects are deleted by the query.
Parameters
| Name |
Type |
Description |
$class |
string |
|
Throws
| Class | Description |
ezcPersistentObjectException |
if there is no such persistent class. |
createFindQuery
Returns a select query for the given persistent object $class.
The query is initialized to fetch all columns from the correct table and has correct alias mappings between columns and property names of the persistent $class. The alias mapping allows you to use property names in WHERE conditions, instead of column names. These aliases will automatically be resolved before querying the database.
Example:
1. <?php
2.
3. $q = $session->createFindQuery( 'Person' );
4. $allPersons = $session->find( $q, 'Person' );
5.
6. ?>
Example with aliases:
1. <?php
2. $q = $session->createFindQuery( 'Person' );
3. $q->where(
4. $q->expr->eq(
5. 'zipCode',
6. $q->bindValue( 12345 )
7. )
8. );
9. $somePersons = $session->find( $q, 'Person' );
10.
11. ?>
$zipCode is the property name in the Person class, while the corresponding database column is named zip_code.
Parameters
| Name |
Type |
Description |
$class |
string |
|
Throws
| Class | Description |
ezcPersistentObjectException |
if there is no such persistent class. |
createFindQueryWithRelations
Returns a select query for the given $class and its related objects as defined in $relations.
The keys of the array define aliases for relations to be used in the local context. Each key has an object of
ezcPersistentRelationFindDefinition assigned, that defines which relation is meant to be fetched. The first entry above assignes the alias 'relationAlias_1' to the related class 'relatedClass_1'. The second parameter to the constructor of {@linke ezcPersistentRelationFindDefinition} can be a relation name, if multiple relations to the same class exist. The third parameter defines deeper relations.
A call to this method with $class set to 'myClass' and $relations defined as seen above creates a find query that by default finds:
- All objects of myClass
- Foreach object of myClass, all related objects of relatedClass_1
- Foreach object of myClass, all related objects of relatedClass_2
- Foreach object of relatedClass_1, all related objects of deeperRelatedClass_1
The aliases defined as the keys of the $relations array can be used to add where() conditions to the created query. Properties of the objects of relatedClass_1 can be accessed by prefixing their name with 'relationAlias_1_' (for example 'relationAlias_1_id' to access the 'id' property).
NOTE: If you restrict the objects to be found by a WHERE condition, not the full set of related objects might be returned. To avoid inconsistencies in the identity map, the extracted sets of related objects will then not be registered as usual, but as
named related
sets. You can retrieve these using the getRelatedObjectSet() method (instead of using
getRelatedObjects()), with the chosen relation alias as the set name.
Parameters
| Name |
Type |
Description |
$class |
string |
|
$relations |
array(ezcPersistentRelationFindDefinition) |
|
See also:
ezcPersistentIdentityMap,
ezcPersistentSessionIdentityDecorator::find(),
ezcPersistentRelationFindDefinition,
ezcPersistentFindWithRelationsQuery.
createRelationFindQuery
Returns the base query for retrieving related objects.
If multiple relations are defined for the $relatedClass (using ezcPersistentRelationCollection), the parameter $relationName becomes mandatory to determine which relation definition to use. For normal relations, this parameter is silently ignored.
If you provide a $setName, the resulting set of related objects fetched by
find() is cached under the given name for $object. You can retrieve this set either through
getRelatedObjectSubset() or by issueing the same query (or a query with the same $object and $setName) again. Overwriting a once created named set can be enfored using the 'refetch' option in
ezcPersistentSessionIdentityDecoratorOptions.
Parameters
| Name |
Type |
Description |
$object |
ezcPersistentObject |
|
$relatedClass |
string |
|
$relationName |
string |
|
$setName |
string |
|
Throws
| Class | Description |
ezcPersistentRelationNotFoundException |
if the given $object does not have a relation to $relatedClass. |
createSubQuery
Returns a sub-select for the given $class to be used with $parentQuery.
This method creates an
ezcPersistentFindQuery as a
ezcQuerySubSelect for the given $class. The returned query has already set aliases for the properties of $class, but (in contrast to the query returned by
createFindQuery()) does not have the selection of all properties set. You need to do
1. <?php
2. $subSelect = $session->subSelect( $existingSelectQuery, 'MyClass' );
3. $subSelect->select( 'myField' );
4. ?>
manually to select the fields you desire.
Parameters
createUpdateQuery
Returns an update query for the given persistent object $class.
The query is initialized to update the correct table and it is only neccessary to set the correct values.
Attention: If you use a query generated by this method to update objects, the internal
ezcPersistentIdentityMap will be completly reset. This is neccessary to avoid inconsistencies, because the session cannot trace which objects are updated by the query.
Parameters
| Name |
Type |
Description |
$class |
string |
|
Throws
| Class | Description |
ezcPersistentDefinitionNotFoundException |
if there is no such persistent class. |
delete
Deletes the persistent $object.
This method will perform a DELETE query based on the identifier of the persistent $object. After delete() the ID property of $object will be reset to null. It is possible to
save() $object afterwards. $object will then be stored with a new ID.
If you defined relations for the given object, these will be checked to be defined as cascading. If cascading is configured, the related objects with this relation will be deleted, too.
The object will also be removed from the identity map and all related object sets in it.
Relations that support cascading are:
- ezcPersistenOneToManyRelation
- ezcPersistenOneToOne
Parameters
Throws
| Class | Description |
ezcPersistentDefinitionNotFoundxception |
if $the object is not recognized as a persistent object. |
ezcPersistentObjectNotPersistentException |
if the object is not persistent already. |
ezcPersistentQueryException |
if the object could not be deleted. |
deleteFromQuery
void deleteFromQuery(
$query )
Deletes persistent objects using the given $query.
Attention: Every call to this method will cause the internal
ezcPersistentIdentityMap to be completly reset. This is neccessary to avoid inconsistencies, because the session cannot trace which objects are updated by the query.
Parameters
Throws
| Class | Description |
ezcPersistentQueryException |
if the delete query failed. |
find
Returns the result of the $query as an array of objects.
Returns the persistent objects found for $class using the submitted $query. $query should be created using
createFindQuery() to ensure correct alias mappings and can be manipulated as needed. The $class parameter is optional, since
ezcPersistentFindQuery now stores this information on creation using
createFindQuery().
The array returned by this method is indexed by the IDs of the contained objects. The order of the array reflects the order in the database or as indicated by the ORDER BY clause of the query.
The results fetched will be checked for identities that have already been recorded before. If an existing identity is found for an object, this identity will be used in the result set. Note: This does not prevent the database query at all, but just ensures consistency.
Example:
1. <?php
2.
3. $q = $session->createFindQuery( 'Person' );
4. $allPersons = $session->find( $q );
5.
6. ?>
If you are retrieving large result set, consider using
findIterator() instead.
Example:
1. <?php
2.
3. $q = $session->createFindQuery( 'Person' );
4. $objects = $session->findIterator( $q, 'Person' );
5.
6. foreach( $objects as $object )
7. {
8. // ...
9. }
10.
11. ?>
Identity mapping comes into action in the following example:
1. <?php
2.
3. $person = $session->load( 'Person', 23 );
4.
5. $q = $session->createFindQuery( 'Person' );
6. $allPersons = $session->find( $q );
7.
8. ?>
In $allPersons, the object with ID 23 will not be a new instance, but the existing instance, that was already fetched by the call to
load().
Parameters
Throws
| Class | Description |
ezcPersistentDefinitionNotFoundException |
if there is no such persistent class. |
ezcPersistentQueryException |
if the find query failed. |
ezcBaseValueException |
if $query parameter is not an instance of ezcPersistentFindQuery or ezcQuerySelect. Or if $class is missing if you use ezcQuerySelect. |
findIterator
Returns the result of $query for the $class as an iterator.
This method is similar to
find() but returns an
ezcPersistentIdentityFindIterator instead of an array of objects. This is useful if you are going to loop over the objects and just need them one at the time. Because you only instantiate one object it is faster than
find(). In addition, only 1 record is retrieved from the database in each iteration, which may reduce the data transfered between the database and PHP, if you iterate only through a small subset of the affected records.
The find interator will automatically look up result objects in the identity map and return existing identities, if they have already been recorded.
Parameters
Throws
| Class | Description |
ezcPersistentDefinitionNotFoundException |
if there is no such persistent class. |
ezcPersistentQueryException |
if the find query failed. |
ezcBaseValueException |
if $query parameter is not an instance of ezcPersistentFindQuery or ezcQuerySelect. Or if $class is missing if you use ezcQuerySelect. |
generateAliasMap
Returns a hash map between property and column name for the given definition $def.
The alias map can be used with the query classes. If $prefixTableName is set to false, only the column names are used as alias targets.
Parameters
getColumnsFromDefinition
Returns all the columns defined in the persistent object.
If $prefixTableName is set to false, raw column names will be used, without prefixed table name.
Parameters
getRelatedObject
object($relatedClass) getRelatedObject(
object
$object, string
$relatedClass, [string
$relationName = null] )
Returns the related object of a given $relatedClass for $object.
This method returns the related object of type $relatedClass for the object $object. This method (in contrast to
getRelatedObjects()) always returns a single result object, no matter if more related objects could be found (e.g.
ezcPersistentOneToManyRelation). If no related object is found, an exception is thrown, while
getRelatedObjects() just returns an empty array in this case.
In case the related object has already been fetched earlier, the request to the database is not repeated, but the recorded object is returned. If the related object was not recorded, yet, it is fetched from the database and recorded afterwards.
Example:
1. $person = $session->load( "Person", 1 );
2. $relatedAddress = $session->getRelatedObject( $person, "Address" );
3. echo "Address of this person: " . $relatedAddress->__toString();
Relations that should preferably be used with this method are:
For other relation types
getRelatedObjects() is recommended.
If multiple relations are defined for the $relatedClass (using ezcPersistentRelationCollection), the parameter $relationName becomes mandatory to determine which relation definition to use. For normal relations, this parameter is silently ignored.
Parameters
| Name |
Type |
Description |
$object |
object |
|
$relatedClass |
string |
|
$relationName |
string |
|
Throws
| Class | Description |
ezcPersistentRelationNotFoundException |
if the given $object does not have a relation to $relatedClass. |
getRelatedObjects
array(int=>object($relatedClass)) getRelatedObjects(
object
$object, string
$relatedClass, [string
$relationName = null] )
Returns the related objects of a given $relatedClass for $object.
In case the set of related objects has already been fetched earlier, the request to the database is not repeated, but the recorded object set is returned. If the set of related objects was not recorded, yet, it is fetched from the database and recorded afterwards.
Example:
1. $person = $session->load( "Person", 1 );
2. $relatedAddresses = $session->getRelatedObjects( $person, "Address" );
3. echo "Number of addresses found: " . count( $relatedAddresses );
Relations that should preferably be used with this method are:
For other relation types
getRelatedObject() is recommended.
If multiple relations are defined for the $relatedClass (using ezcPersistentRelationCollection), the parameter $relationName becomes mandatory to determine which relation definition to use. For normal relations, this parameter is silently ignored.
Parameters
| Name |
Type |
Description |
$object |
object |
|
$relatedClass |
string |
|
$relationName |
string |
|
Throws
| Class | Description |
ezcPersistentRelationNotFoundException |
if the given $object does not have a relation to $relatedClass. |
getRelatedObjectSubset
array(ezcPersistentObject)|null getRelatedObjectSubset(
ezcPersistentObject
$object, string
$setName )
Returns the named related object subset with $setName for $object.
Parameters
See also:
ezcPersistentSessionIdentityDecorator::createFindQueryWithRelations(),
ezcPersistentSessionIdentityDecorator::find(),
ezcPersistentFindWithRelationsQuery.
isRelated
Returns if $relatedObject is related to $sourceObject.
Checks the relation conditions between $sourceObject and $relatedObject and returns true, if $relatedObject is related to $sourceObject, otherwise false. Relation state is determined through the identity map, in case the relation between $sourceObject and $relatedObject has been recorded there. Otherwise this method dispatches to
ezcPersistentSession::isRelated().
In case multiple relations are defined between the classes of $sourceObject and $relatedObject, the $relationName parameter becomes mandatory. If it is not provided in this case, an
ezcPersistentUndeterministicRelationException is thrown.
Note that checking relations of type
ezcPersistentManyToManyRelation will issue a database query, if the relation is not recorded in the identity map. Other relations will not perform this query at all.
Parameters
load
Returns the persistent object of class $class with id $id.
Checks if the object of $class with $id has already been loaded. If this is the case, the existing identity is returned. Otherwise the desired object is loaded from the database and its identity is recorded for later uses.
Parameters
| Name |
Type |
Description |
$class |
string |
|
$id |
mixed |
|
Throws
| Class | Description |
ezcPersistentObjectException |
if there is no such persistent $class. |
ezcPersistentObjectException |
if the object is not available. |
loadIfExists
Returns the persistent object of class $class with id $id or null.
This method is equivalent to
load() except that it returns null instead of throwing an exception, if the desired object does not exist. A null value will not be recorded in the identity map, so a second attempt to load the object of $class with $id will result in another database query.
Parameters
| Name |
Type |
Description |
$class |
string |
|
$id |
int |
|
loadIntoObject
Loads the persistent object of $class with $id into the given $object.
The class of the persistent object to load is determined from $object. In case an identity for the given $id has already been recorded in the identity map and $object is not the same instance, an exception is thrown.
Parameters
Throws
| Class | Description |
ezcPersistentObjectException |
if the object is not available. |
ezcPersistentIdentityAlreadyExistsException |
if a different identity of the class of $object with $id already exists. |
ezcPersistentDefinitionNotFoundException |
if $object is not of a valid persistent object type. |
ezcPersistentQueryException |
if the find query failed. |
loadWithRelatedObjects
Loads an object of $class with $id and related objects defined by $relations.
This method loads and returns the object of $class with $id. In addition, all objects defined by $relations are loaded and fetched into the identity map. Those can then be retrieved using
getRelatedObjects(), without issueing further database queries.
Each relation is defined by an
ezcPersistentRelationFindDefinition struct This defines the related class to load objects for, optionally a relation name (second parameter) and possibly an array of deeper relations. All array keys on all levels of the $relations parameter must be unique!
In the example, if $class is 'myClass' and $id is 23, the object of myClass with ID 23 is loaded and returned. In addition, all objects of relatedClass_1 and relatedClass_2, that related to the loaded object, are loaded and stored in the identity map. For each of these objects of class relatedClass_1, all related objects of class deeperRelatedClass_1 are loaded and also stored in the identity map.
Parameters
| Name |
Type |
Description |
$class |
string |
|
$id |
string |
|
$relations |
array(string=>ezcPersistentRelationFindDefinition) |
|
See also:
ezcPersistentSessionIdentityDecorator::createFindQueryWithRelations().
refresh
Syncronizes the contents of $object with the database.
Note that calling this method is equavalent with calling
loadIntoObject() on $object with the ID of $object. Any changes made to $object prior to calling refresh() will be discarded.
The refreshing of an object will result in its identity being refreshed automatically.
Parameters
Throws
| Class | Description |
ezcPersistentObjectException |
if $object is not of a valid persistent object type. |
ezcPersistentObjectException |
if $object is not persistent already. |
ezcPersistentObjectException |
if the select query failed. |
removeRelatedObject
Removes the relation between $object and $relatedObject.
This method is used to delete an existing relation between 2 objects. Like
addRelatedObject() this method does not store the related object after removing its relation properties (unset), except for ezcPersistentManyToManyRelation()s, for which the relation record is deleted from the database.
If between the classes of $object and $relatedObject multiple relations are defined using a ezcPersistentRelationCollection, the $relationName parameter becomes necessary. It defines which exact relation to affect here.
Removal of related objects is reflected in the identity map automatically and also in named related object sets.
Parameters
Throws
| Class | Description |
ezcPersistentRelationNotFoundException |
if the deisred relation is not defined. |
ezcPersistentRelationOperationNotSupportedException |
if a relation to create is marked as "reverse". |
save
Saves the new persistent object $object to the database using an INSERT INTO query.
Newly saved objects are stored in the identity map.
Parameters
Throws
| Class | Description |
ezcPersistentObjectException |
if $object is not of a valid persistent object type. |
ezcPersistentObjectException |
if the insert query failed. |
ezcPersistentObjectException |
if $object is already stored to the database. |
ezcPersistentObjectException |
if it was not possible to generate a unique identifier for the new object. |
saveOrUpdate
Saves or updates the persistent $object to the database.
If the object is a new object an INSERT INTO query will be executed. If the object is persistent already it will be updated with an UPDATE query.
Newly saved objects are automatically recorded in the identity map. Updates to existing objects are reflected automatically, too.
Parameters
Throws
| Class | Description |
ezcPersistentDefinitionNotFoundException |
if the definition of the persistent object could not be loaded. |
ezcPersistentObjectException |
if the insert or update query failed. |
ezcPersistentObjectException |
if $object is not of a valid persistent object type. |
ezcPersistentObjectException |
if any of the definition requirements are not met. |
update
Updates $object in the database using an UPDATE query.
Stores the changes made to $object into the database. Updates are automatically reflected in the identity map.
Parameters
Throws
| Class | Description |
ezcPersistentDefinitionNotFoundException |
if $object is not of a valid persistent object type. |
ezcPersistentObjectNotPersistentException |
if $object is not stored in the database already. |
ezcPersistentQueryException |
|
updateFromQuery
void updateFromQuery(
$query )
Updates persistent objects using the query $query.
The $query should be created using createUpdateQuery().
Currently this method only executes the provided query. Future releases PersistentSession may introduce caching of persistent objects. When caching is introduced it will be required to use this method to run cusom delete queries. To avoid being incompatible with future releases it is advisable to always use this method when running custom delete queries on persistent objects.
Attention: Every call to this method will cause the internal
ezcPersistentIdentityMap to be completly reset. This is neccessary to avoid inconsistencies, because the session cannot trace which objects are updated by the query.
Parameters
Throws
| Class | Description |
ezcPersistentQueryException |
if the update query failed. |
Last updated: Mon, 21 Dec 2009