https://github.com/gjerokrsteski/php-identity-map
Building an Identity Map in PHP
https://github.com/gjerokrsteski/php-identity-map
data-mapper identity-map oop pdo php
Last synced: 5 months ago
JSON representation
Building an Identity Map in PHP
- Host: GitHub
- URL: https://github.com/gjerokrsteski/php-identity-map
- Owner: gjerokrsteski
- Created: 2011-10-27T14:09:43.000Z (about 14 years ago)
- Default Branch: master
- Last Pushed: 2012-07-07T08:47:14.000Z (over 13 years ago)
- Last Synced: 2025-05-16T13:44:31.998Z (6 months ago)
- Topics: data-mapper, identity-map, oop, pdo, php
- Language: PHP
- Homepage:
- Size: 203 KB
- Stars: 19
- Watchers: 3
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.markdown
Awesome Lists containing this project
README
Building an Identity Map in PHP
===============================
Sample application used for training.
This example code is no production code and should be used for training
purposes only.
This example code requires:
---------------------------
* PDO a lightweight, consistent interface for accessing databases in PHP.
* PHPUnit a unit testing framework for PHP projects.
This example code implements:
-----------------------
* Data-Mapper Pattern
* Identity-Map Pattern
Why identity mapping?
---------------------
By using Data-Mapper pattern without an identity map, you can easily run
into problems because you may have more than one object that references
the same domain entity.
Data-Mapper without identity map
----------------------------------
$userMapper = new UserMapper($pdo);
$user1 = $userMapper->find(1); // creates new object
$user2 = $userMapper->find(1); // creates new object
echo $user1->getNickname(); // joe123
echo $user2->getNickname(); // joe123
$user1->setNickname('bob78');
echo $user1->getNickname(); // bob78
echo $user2->getNickname(); // joe123 -> ?!?
Data-Mapper with identity map
----------------------------------
The identity map solves this problem by acting as a registry for all
loaded domain instances.
$userMapper = new UserMapper($pdo);
$user1 = $userMapper->find(1); // creates new object
$user2 = $userMapper->find(1); // returns same object
echo $user1->getNickname(); // joe123
echo $user2->getNickname(); // joe123
$user1->setNickname('bob78');
echo $user1->getNickname(); // bob78
echo $user2->getNickname(); // bob78 -> yes, much better
By using an identity map you can be confident that your domain entity is
shared throughout your application for the duration of the request.
Note that using an identity map is not the same as adding a cache layer
to your mappers. Although caching is useful and encouraged, it can still
produce duplicate objects for the same domain entity.
Load the Data-Mappers with the Repository class
-----------------------------------------------
$repository = new Repository($this->db);
$userMapper = $repository->load('User');
$insertId = $userMapper->insert(new User('billy', 'gatter'));