Slide 1

Slide 1 text

CREATING YOUR OWN ENTITY/OBJECT MANAGER Jachim Coudenys / jachim.be @coudenysj

Slide 2

Slide 2 text

ABOUT ME Jachim Coudenys ( ) (Ab)Using PHP since 2002 (4.1.0) @coudenysj

Slide 3

Slide 3 text

KING FOO Developer at King Foo ( ) http://king-foo.be SYMFONY2 TRAINING SensioLabs partner SF4PHPBNL http://training.king-foo.be

Slide 4

Slide 4 text

PHP-WVL Co-Organizer of PHP-WVL ( ) http://php-wvl.be

Slide 5

Slide 5 text

$user = new User(); $user->setName('Jachim Coudenys'); $user->setEmail('[email protected]'); $em->persist($user); $em->flush(); $user = $em->find('User', 123); $user->setEmail('[email protected]'); $em->flush(); Who recognizes this? Who is using this? Who loves using this?

Slide 6

Slide 6 text

WHAT?

Slide 7

Slide 7 text

define EntityManager The EntityManager API is used to access a database in a particular unit of work. It is used to create and remove persistent entity instances, to find entities by their primary key identity, and to query over all entities. ( ) http://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/architecture.html

Slide 8

Slide 8 text

WHY?

Slide 9

Slide 9 text

TIME FOR SOME HISTORY Small extraction of my presentation. The Database Access rEvolution (with @miljar)

Slide 10

Slide 10 text

FILES Textbook example: guestbook

Slide 11

Slide 11 text

-FUNCTIONS cubrid_* dbplus_* dbase_* filepro_* ibase_* fbsql_* db2_* ifx_* ingres_* maxdb_* msql_* mssql_* mysql_ oci_* ovrimos_* px_* pg_* sqlite_* sqlsrv_* sybase_*

Slide 12

Slide 12 text

PDO The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP ( ) PHP.net manual

Slide 13

Slide 13 text

ORM FRAMEWORK Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in relational databases and object- oriented programming languages ( ) Wikipedia

Slide 14

Slide 14 text

ORM FRAMEWORK: ACTIVE RECORD An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data. ( ) PoEAA: Active Record Doctrine 1.x

Slide 15

Slide 15 text

ORM FRAMEWORK: GATEWAYS An object that encapsulates access to an external system or resource ( ) PoEAA: Gateway Zend_Db_Table Zend_Db_Table_Row

Slide 16

Slide 16 text

ORM FRAMEWORK: DATA MAPPER A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself. ( ) PoEAA: Data Mapper Doctrine 2

Slide 17

Slide 17 text

ORM FRAMEWORK: DATA MAPPER This is where an entity/object manager enters the stage.

Slide 18

Slide 18 text

NO REALLY, WHY? Use code that most people recognize Separation of responsibilities Better overview Because you can

Slide 19

Slide 19 text

VARIANTS We will write our own variant, but many exist already ORM ODM Object Document Mapper OGM Object Graph Mapper Etc... Object Relational Mapper Mongo CouchDB PHPCR Neo4j-PHP-OGM

Slide 20

Slide 20 text

HOW?

Slide 21

Slide 21 text

LET'S GET STARTED We want to talk to a SOAP server We want to use entities to send data back and forth We will only implement what we need

Slide 22

Slide 22 text

EXTENDING THE ENTITY MANAGER Let's open the Doctrine\ORM\EntityManager class The class DocBlock says: You should never attempt to inherit from the EntityManager: Inheritance is not a valid extension point for the EntityManager. Instead you should take a look at the {@see \Doctrine\ ORM\ Decorator\ EntityManagerDecorator} and wrap your entity manager in a decorator.

Slide 23

Slide 23 text

ENTITYMANAGER DECORATOR namespace Doctrine\ORM\Decorator; use Doctrine\DBAL\LockMode; use Doctrine\ORM\Query\ResultSetMapping; use Doctrine\ORM\EntityManagerInterface; use Doctrine\Common\Persistence\ObjectManagerDecorator; abstract class EntityManagerDecorator extends ObjectManagerDecorator implements EntityManagerInterface { /** * @var EntityManagerInterface */ protected $wrapped; /** * @param EntityManagerInterface $wrapped */ public function __construct(EntityManagerInterface $wrapped) { $this->wrapped = $wrapped; } /** Allows you to override specific methods Still ORM oriented A lot of stuff we won't actually use

Slide 24

Slide 24 text

OBJECTMANAGER namespace Doctrine\Common\Persistence; interface ObjectManager { /** * Finds an object by its identifier. * * This is just a convenient shortcut for getRepository($className)->find($ * * @param string $className The class name of the object to find. * @param mixed $id The identity of the object to find. * * @return object The found object. */ public function find($className, $id); /** * Tells the ObjectManager to make an instance managed and persistent. * * The object will be entered into the database as a result of the flush op * * NOTE: The persist operation always considers objects that are not yet kn * this ObjectManager as NEW. Do not pass detached objects to the persist o * * @param object $object The instance to make managed and persistent. * Base for all (or most) variants More than enough for now Start with throw exception at first and implement what you need

Slide 25

Slide 25 text

SETUP "Inject" a connection and config namespace My\Project; use Doctrine\Common\Persistence\ObjectManager; use My\Project\Service\SoapClient; class EntityManager implements ObjectManager { /** * @param SoapClient $conn * @param mixed $config */ protected function __construct(SoapClient $conn, $config) { $this->conn = $conn; $this->config = $config; } }

Slide 26

Slide 26 text

find /** * Finds an object by its identifier. * * This is just a convenient shortcut for * getRepository($className)->find($id). * * @param string $className The class name of the object to find. * @param mixed $id The identity of the object to find. * * @return object The found object. */ public function find($className, $id);

Slide 27

Slide 27 text

getRepository /** * Gets the repository for a class. * * @param string $className * * @return \Doctrine\Common\Persistence\ObjectRepository */ public function getRepository($className);

Slide 28

Slide 28 text

REPOSITORY Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects. http://www.martinfowler.com/eaaCatalog/repository.html

Slide 29

Slide 29 text

getRepository public function getRepository($className) { if (!array_key_exists($className, $this->repositories)) { $repositoryName = str_replace( 'Entity', 'Repository', $className ); $repositoryName .= 'Repository'; $repository = new $repositoryName($this); $this->repositories[$className] = $repository; } return $this->repositories[$className]; } My\Project\Entity\User My\Project\Repository\UserRepository

Slide 30

Slide 30 text

CUSTOM REPOSITORY namespace Doctrine\Common\Persistence; interface ObjectRepository { /** * Finds an object by its primary key / identifier. * * @param mixed $id The identifier. * * @return object The object. */ public function find($id); /** * Finds all objects in the repository. * * @return array The objects. */ public function findAll(); /** * Finds objects by a set of criteria.

Slide 31

Slide 31 text

MAPPING Holds details of object-relational mapping in metadata. http://www.martinfowler.com/eaaCatalog/metadataMapping.html

Slide 32

Slide 32 text

getMetadataFactory /** * Gets the metadata factory used to gather the metadata of classes. * * @return \Doctrine\Common\Persistence\Mapping\ClassMetadataFactory */ public function getMetadataFactory();

Slide 33

Slide 33 text

getClassMetadata /** * Returns the ClassMetadata descriptor for a class. * * The class name must be the fully-qualified class name without a * leading backslash (as it is returned by get_class($obj)). * * @param string $className * * @return \Doctrine\Common\Persistence\Mapping\ClassMetadata */ public function getClassMetadata($className);

Slide 34

Slide 34 text

Doctrine\Common\Persistenc e\Mapping\ClassMetadata namespace Doctrine\Common\Persistence\Mapping; interface ClassMetadata { /** * Gets the fully-qualified class name of this persistent class. * * @return string */ public function getName(); /** * Gets the mapped identifier field name. * * The returned structure is an array of the identifier field names. * * @return array */ public function getIdentifier();

Slide 35

Slide 35 text

getRepository public function getRepository($className) { if (!array_key_exists($className, $this->repositories)) { $classMetadata = $this->getClassMetadata($className); // Doctrine ORM approach $repositoryName = $classMetadata->customRepositoryClassName; $repository = new $repositoryName($this, $classMetadata); $this->repositories[$className] = $repository; } return $this->repositories[$className]; }

Slide 36

Slide 36 text

FIND VIA REPOSITORY namespace My\Project\Repository; use Doctrine\Common\Persistence\ObjectRepository; class UserRepository implements ObjectRepository { public function find($id) { $response = $this->getEntityManager() ->getConnection()->call('UserGet', ['userId' => $id]); // ... // return User entity? } }

Slide 37

Slide 37 text

HYDRATION Hydration is the act of populating an object from a set of data. http://framework.zend.com/manual/current/en/modules/zend.stdlib.hydrator.html

Slide 38

Slide 38 text

DATA HYDRATORS http://doctrine.readthedocs.org/en/latest/en/manual/data-hydrators.html Query::HYDRATE_OBJECT Query::HYDRATE_ARRAY Query::HYDRATE_SCALAR Query::HYDRATE_SINGLE_SCALAR

Slide 39

Slide 39 text

RETURN AN ENTITY IN FIND // UserRepository public function find($id) { // ... $user = new User(); $hydrator = new \Zend\Stdlib\Hydrator\ClassMethods(); $hydrator->hydrate($response, $user); return $user; } Improvements: $this->em->getHydrator($classname); Work with the mapping

Slide 40

Slide 40 text

ENTITIES Now we have a list of objects with an identifier We can (or need to) keep track of these in the OM

Slide 41

Slide 41 text

IDENTITY MAP Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them. http://www.martinfowler.com/eaaCatalog/identityMap.html

Slide 42

Slide 42 text

IDENTITY MAP namespace My\Project; use Doctrine\Common\Persistence\ObjectManager; class EntityManager implements ObjectManager { /** * Collection of identities: * array( * 'User' => [1 => object, 5 => object], * // ... * ) */ private $identityMap = array(); public function find($className, $id) { // check map first // store in map } // ...

Slide 43

Slide 43 text

OBJECT STATES EXISTING OBJECTS $user = $em->find('User', 123); $user->setEmail('[email protected]'); $em->flush(): NEW OBJECTS $user = new User(); $user->setName('Jachim Coudenys'); $user->setEmail('[email protected]'); $em->persist($user); $em->flush();

Slide 44

Slide 44 text

OBJECT STATES STATE_MANAGED STATE_NEW STATE_DETACHED STATE_REMOVED

Slide 45

Slide 45 text

UNIT OF WORK Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems. http://www.martinfowler.com/eaaCatalog/unitOfWork.html

Slide 46

Slide 46 text

UNIT OF WORK Can be an object in the OM (Doctrine) Can be a construction in the OM

Slide 47

Slide 47 text

persist /** * Tells the ObjectManager to make an instance managed and * persistent. The object will be entered into the database as * a result of the flush operation. * * NOTE: The persist operation always considers objects that * are not yet known to this ObjectManager as NEW. Do not pass * detached objects to the persist operation. * * @param object $object The instance to make managed and persistent * * @return void */ public function persist($object);

Slide 48

Slide 48 text

persist IMPLEMENTED class EntityManager implements ObjectManager { private $entities = array(); public function persist($object) { $this->entities[spl_object_hash($object)] = $object; } }

Slide 49

Slide 49 text

remove /** * Removes an object instance. * * A removed object will be removed from the database as a * result of the flush operation. * * @param object $object The object instance to remove. * * @return void */ public function remove($object);

Slide 50

Slide 50 text

remove IMPLEMENTED class EntityManager implements ObjectManager { private $entitiesToRemove = array(); public function remove($object) { $this->entitiesToRemove[spl_object_hash($object)] = $object; } }

Slide 51

Slide 51 text

contains /** * Checks if the object is part of the current UnitOfWork * and therefore managed. * * @param object $object * * @return bool */ public function contains($object);

Slide 52

Slide 52 text

merge /** * Merges the state of a detached object into the persistence * context of this ObjectManager and returns the managed copy * of the object. The object passed to merge will not become * associated/managed with this ObjectManager. * * @param object $object * * @return object */ public function merge($object);

Slide 53

Slide 53 text

refresh /** * Refreshes the persistent state of an object from the database, * overriding any local changes that have not yet been persisted. * * @param object $object The object to refresh. * * @return void */ public function refresh($object);

Slide 54

Slide 54 text

detach /** * Detaches an object from the ObjectManager, causing a managed * object to become detached. Unflushed changes made to the * object if any (including removal of the object), will not be * synchronized to the database. Objects which previously referenced * the detached object will continue to reference it. * * @param object $object The object to detach. * * @return void */ public function detach($object);

Slide 55

Slide 55 text

clear /** * Clears the ObjectManager. All objects that are currently managed * by this ObjectManager become detached. * * @param string|null $objectName if given, only objects of * this type will get detached. * * @return void */ public function clear($objectName = null);

Slide 56

Slide 56 text

flush /** * Flushes all changes to objects that have been queued up to now * to the database. This effectively synchronizes the in-memory * state of managed objects with the database. * * @return void */ public function flush();

Slide 57

Slide 57 text

flush IMPLEMENTED class EntityManager implements ObjectManager { public function flush() { // - loop over $this->entities and save them // - optionally set the identifier of the entity // - update the states of the entities // - loop over $this->entitiesToRemove and delete them // - reset $this->entitiesToRemove } }

Slide 58

Slide 58 text

flush IMPROVED class EntityManager implements ObjectManager { private $entities; private $originalEntities; public function flush() { // actually use a "Unit of Work" object to calculate // changed values between // $this->originalEntities and $this->entities // ... } }

Slide 59

Slide 59 text

flush HACKED EXAMPLE class EntityManager implements ObjectManager { private $entities; private $originalEntities; public function flush() { foreach ($this->entities as $entity) { // keep some SOAP logic together $this->getRepository(get_class($entity)) ->flush($entity); } } }

Slide 60

Slide 60 text

flush HACKED EXAMPLE class UserRepository extends ObjectRepository { public function flush(User $user) { $changedValues = // calculate diffs // different SOAP calls if (array_key_exists('password', $changedValues)) { $this->getEntityManager() ->getConnection()->call( 'UpdatePassword', ['userId' => $user->getId(), 'password' => $changedValues['password']] ); } // etc ... } }

Slide 61

Slide 61 text

initializeObject /** * Helper method to initialize a lazy loading proxy * or persistent collection. * * This method is a no-op for other objects. * * @param object $obj * * @return void */ public function initializeObject($obj);

Slide 62

Slide 62 text

LAZY LOADING An object that doesn't contain all of the data you need but knows how to get it. http://www.martinfowler.com/eaaCatalog/lazyLoad.html

Slide 63

Slide 63 text

THE PROXY PATTERN IN PHP http://ocramius.github.io/presentations/proxy-pattern-in- php/

Slide 64

Slide 64 text

OBJECTMANAGER interface ObjectManager { public function find($className, $id); public function persist($object); public function remove($object); public function merge($object); public function clear($objectName = null); public function detach($object); public function refresh($object); public function flush(); public function getRepository($className); public function getClassMetadata($className); public function getMetadataFactory(); public function initializeObject($obj); public function contains($object); }

Slide 65

Slide 65 text

WELCOME, OBJECT MANAGER

Slide 66

Slide 66 text

EXTRA BITS

Slide 67

Slide 67 text

CACHING 3 types of Metadata Cache Query Cache Result Cache Your turn on repositories Other Doctrine caching ObjectCache

Slide 68

Slide 68 text

QUERY OBJECT An object that represents a database query. http://www.martinfowler.com/eaaCatalog/queryObject.html

Slide 69

Slide 69 text

OTHER VARIANTS Elasticsearch Suggestions?

Slide 70

Slide 70 text

CONCLUSION A lot of variants exist already Not that hard (only take what you need) Check if you can start by extending the ORM (if you are working relational) Use the ObjectManager interface for the rest

Slide 71

Slide 71 text

RESOURCES http://doctrine- orm.readthedocs.org/en/latest/reference/unitofwork.html http://www.martinfowler.com/books/eaa.html

Slide 72

Slide 72 text

THANK YOU https://joind.in/13180 @coudenysj king-foo.be php-wvl.be QUESTIONS?