Symfony2 and Doctrine2 Integration

download Symfony2 and Doctrine2 Integration

of 55

  • date post

    08-May-2015
  • Category

    Documents

  • view

    29.757
  • download

    0

Embed Size (px)

Transcript of Symfony2 and Doctrine2 Integration

  • 1.Symfony and DoctrineWhats new in the Symfony and Doctrine Integration Doctrine 2 www.doctrine-project.orgwww.sensiolabs.com

2. Updated DoctrineBundle Doctrine2 features fully integrated Database Abstraction Layer Object Relational Mapper Doctrine 2www.doctrine-project.org www.sensiolabs.com 3. DoctrineMongoDBBundle MongoDB Object Document Mapper Transparent persistence to MongoDB Same architecture as ORM Map a class as an entity and document Doctrine 2www.doctrine-project.org www.sensiolabs.com 4. DoctrineMigrationsBundle Integration with the database migrations project. Easily manage and deploy different versions of your database. Generate migrations when you change your schema mapping informationDoctrine 2www.doctrine-project.org www.sensiolabs.com 5. DBAL To use just the DBAL you must congure it:doctrine.dbal: dbname: Symfony user: root password: ~ Doctrine 2 www.doctrine-project.org www.sensiolabs.com 6. DBAL If you need to specify multiple connections you can use the following syntax:doctrine.dbal:default_connection: defaultconnections:default:driver: PDOSqlitedbname: Symfonyuser: rootpassword: nullhost: localhostport: ~path: %kernel.data_dir%/symfony.sqliteevent_manager_class:DoctrineCommonEventManagerconfiguration_class:DoctrineDBALConfigurationwrapper_class:~options:[] Doctrine 2 www.doctrine-project.org www.sensiolabs.com 7. DBAL Console Commands Create all congured databases$ php console doctrine:database:create Create a specic database$ php console doctrine:database:create --connection=default Drop all congured databases$ php console doctrine:database:drop Drop a specic database$ php console doctrine:database:drop --connection=default Doctrine 2 www.doctrine-project.org www.sensiolabs.com 8. DBAL Console Commands Execute SQL queries$ php console doctrine:query:sql SELECT * FROM user Specify connection$ php console doctrine:query:sql ... --connection=default Doctrine 2 www.doctrine-project.org www.sensiolabs.com 9. DBAL Get the default congured database connection:class MyController extends DoctrineController{public function indexAction(){$conn = $this->getDatabaseConnection(); // ...}} Doctrine 2 www.doctrine-project.org www.sensiolabs.com 10. DBAL Get a congured database connection service by its name:class MyController extends DoctrineController{public function indexAction(){$conn = $this->getDatabaseConnection('default'); // ...}} Doctrine 2www.doctrine-project.org www.sensiolabs.com 11. ORM The EntityManager Central place for persisting and retrieving entities Multiple instances allowed One EntityManager per database connection$config = new DoctrineORMConfiguration();$config->setMetadataCacheImpl(new DoctrineCommonCacheArrayCache);$driverImpl = $config->newDefaultAnnotationDriver(array(__DIR__."/Entities"));$config->setMetadataDriverImpl($driverImpl); $config->setProxyDir(__DIR__ . '/Proxies');$config->setProxyNamespace('Proxies'); $connectionOptions = array('driver' => 'pdo_sqlite','path' => 'database.sqlite'); $em = DoctrineORMEntityManager::create($connectionOptions, $config); Dependency Injection handles the creation andmanagement of entity manager services Doctrine 2www.doctrine-project.orgwww.sensiolabs.com 12. ORM What is an Entity? It is a regular PHP object that has been mapped to the Doctrine2 ORM: /** @Entity */ class User { /*** @Id @Column(type="integer")* @GeneratedValue*/ private $id;/** @Column(type="string", length=255) */ private $name;public function getId() { return $this->id; }public function getName() { return $this->name; }public function setName($name) { $this->name = $name; } } Doctrine 2 www.doctrine-project.orgwww.sensiolabs.com 13. ORM No more magic in your domain Clean and testable Fast! Only limited by what you can do with PHP OO to design your domain Inheritance Use __construct() without any problems Entities are persisted transparently by the EntityManagerDoctrine 2 www.doctrine-project.orgwww.sensiolabs.com 14. ORM Congure an entity manager to start using the ORM:doctrine.orm: default_entity_manager: default cache_driver: apc# array, apc, memcache, xcache entity_managers: default: connection: default Doctrine 2 www.doctrine-project.org www.sensiolabs.com 15. ORM Console commands implemented for improved developer workow: Doctrine 2 www.doctrine-project.orgwww.sensiolabs.com 16. ORM Console commands implemented for improved developer workow: Ensure production settings Clear metadata, query and result cache Load data xtures Create and drop congured databases Generate entities from mapping information Generate new skeleton entities Generate skeleton entity repository classes Convert mapping information between formats Convert a Doctrine1 schema Import mapping information from an existing database Execute DQL and SQL queries Create, drop and update database schema from mapping information Doctrine 2www.doctrine-project.orgwww.sensiolabs.com 17. ORM Get the default congured entity manager service: class MyController extends DoctrineController{public function indexAction(){$em = $this->getEntityManager(); // ...}} Doctrine 2 www.doctrine-project.orgwww.sensiolabs.com 18. ORM Get a congured entity manager service by its name: class MyController extends DoctrineController{public function indexAction(){$em = $this->getEntityManager('default'); // ...}} Doctrine 2 www.doctrine-project.orgwww.sensiolabs.com 19. ORM Persisting entities is as simple as creating the object and telling Doctrine to persist it:class MyController extends DoctrineController{public function createAction(){$em = $this->getEntityManager(); $user = new User();$user->setName('Jonathan H. Wage');$em->persist($user);$em->flush(); // ...}}Doctrine 2 www.doctrine-project.orgwww.sensiolabs.com 20. ORM Creating Query instances and issue DQL queries to retrieve objects:class MyController extends DoctrineController{public function indexAction(){$em = $this->getEntityManager();$query = $em->createQuery('select u from MyBundle:User u'); $users = $query->execute(); // ...}} Doctrine 2www.doctrine-project.org www.sensiolabs.com 21. ORM Creating QueryBuilder instances to programatically build DQL queries through a uent interface: class MyController extends DoctrineController { public function indexAction() { $em = $this->getEntityManager(); $qb = $em->createQueryBuilder() ->select('u') ->from('MyBundle:User', 'u');$query = $qb->getQuery(); $users = $query->execute();// ... } }Doctrine 2 www.doctrine-project.orgwww.sensiolabs.com 22. ORM Update your database schema during development as your domain model evolves Add a new column to our User entity/** @Entity */class User{// .../** @Column(type="string", length=255) */ private $email;}Doctrine 2 www.doctrine-project.orgwww.sensiolabs.com 23. ORM Run update command to update your database schema from mapping information $ php console doctrine:schema:update The above compares your current database schema to your new mapping information and executes the necessary queries to bring your database up-to-date. Doctrine 2www.doctrine-project.orgwww.sensiolabs.com 24. Object Document Mapper New Doctrine Project for persisting objects to MongoDB Same architecture as ORM Transparently persist PHP5 objects to MongoDB Doctrine 2www.doctrine-project.org www.sensiolabs.com 25. MongoDB ODM The DocumentManager Central place for persisting and retrieving documents Multiple instances allowed$config = new Configuration(); $config->setProxyDir(__DIR__ . '/Proxies');$config->setProxyNamespace('Proxies');$config->setDefaultDB('doctrine_odm_sandbox'); $reader = new AnnotationReader();$reader->setDefaultAnnotationNamespace('DoctrineODMMongoDBMapping');$config->setMetadataDriverImpl(new AnnotationDriver($reader, __DIR__ . '/Documents')); $dm = DocumentManager::create(new Mongo(), $config); Dependency Injection handles the creation andmanagement of document manager services Doctrine 2www.doctrine-project.orgwww.sensiolabs.com 26. MongoDB ODM To use the MongoDB ODM you must congure it: doctrine_odm.mongodb:default_document_manager: defaultcache_driver: arraydocument_managers:default:connection: mongodbconnections:mongodb:server: localhost/somedatabase Doctrine 2 www.doctrine-project.org www.sensiolabs.com 27. MongoDB ODM If the defaults are good enough for you then you can omit all the previous options: doctrine_odm.mongodb: ~ Doctrine 2 www.doctrine-project.org www.sensiolabs.com 28. MongoDB ODM What is a Document? It is a regular PHP object that has been mapped to the MongoDB ODM: /** @Document */ class User { /*** @Id*/ private $id;/** @String */ private $name;public function getId() { return $this->id; }public function getName() { return $this->name; }public function setName($name) { $this->name = $name; } } Doctrine 2 www.doctrine-project.orgwww.sensiolabs.com 29. MongoDB ODM Get the default congured document manager: class MyController extends DoctrineController{public function indexAction(){$dm = $this->getDocumentManager(); // ...}} Doctrine 2 www.doctrine-project.org www.sensiolabs.com 30. MongoDB ODM Get a congured document manager by its name: class MyController extends DoctrineController{public function indexAction(){$dm = $this->getDocumentManager('default'); // ...}} Doctrine 2 www.doctrine-project.org www.sensiolabs.com 31. MongoDB ODM Just like the ORM persisting documents is easy:class MyController extends DoctrineController{public function createAction(){$dm = $this->getDocumentManager(); $user = new User();$user->setName('Jonathan H. Wage');$dm->persist($user);$dm->flush(); // ...}}Doctrine 2 www.doctrine-project.orgwww.sensiolabs.com 32. MongoDB ODM Change tracking All objects are tracked in an identity map Changesets are calculated on ush Changesets are used to perform updates usingthe atomic operators The following code results in an efficient mongo upd