SlideShare una empresa de Scribd logo
1 de 26
Descargar para leer sin conexión
Karsten Dambekalns




       Persistence in FLOW3
            with Doctrine 2


               FLOW3 Experience 2012

                                       1
Karsten Dambekalns

co-lead of TYPO3 5.0 and FLOW3

34 years old

lives in Lübeck, Germany

1 wife, 3 sons, 1 espresso machine

likes canoeing and climbing




                                     2
Persistence in FLOW3 with Doctrine 2

Object Persistence in the Flow
 • Based on Doctrine 2

 • Seamless integration into FLOW3

 • Provides the great Doctrine 2 features

 • Uses UUIDs

 • Our low-level persistence API

   • Allows for own, custom persistence
     backends (instead of Doctrine 2)

   • CouchDB is supported natively

                                            3
Basic Object Persistence

    • Get your repository injected conveniently

    • Handle your objects (almost) like you had no framework


	 	 // Create a new customer and persist it:
	 $customer = new Customer("Robert");
	 $this->customerRepository->add($customer);

	 	 // Update a customer:
	 $customer->setName("I, Robot");
	 $this->customerRepository->update($customer);

	   	 // Find an existing customer:
	   $otherCustomer = $this->customerRepository->findByFirstName("Karsten");
	
	   	 // … and delete it:
	   $this->customerRepository->remove($otherCustomer);



                                                                              4
Persistence in FLOW3 with Doctrine 2

Differences to plain Doctrine 2 in modeling
• Identifier properties are added transparently

• FLOW3 does autodetection for

 • repository class names, column types, referenced column names

 • target entity types, cascade attributes

• All Doctrine annotations work as usual

 • Whatever you specify wins over automation

 • Allows for full flexibility


                                                                   5
Purely Doctrine 2
       use DoctrineORMMapping as ORM;

       /**
        * @ORMEntity(repositoryClass="BugRepository")
        */
       class Bug {

       	 /**
       	    * @var integer
       	    * @ORMId
         	 * @ORMColumn(type="integer")
       	    * @ORMGeneratedValue
       	    */
           protected $id;

       	 /**
       	  * @var string
       	  * @ORMColumn(type="string")
       	  */
         protected $description;

           /**
            * @var DateTime
            * @ORMColumn(type="datetime")
            */                                           6
Doctrine 2 in FLOW3
       use DoctrineORMMapping as ORM;

       /**
        * @ORMEntity(repositoryClass="BugRepository")
        */
       class Bug {

       	 /**
       	    * @var integer
       	    * @ORMId
         	 * @ORMColumn(type="integer")
       	    * @ORMGeneratedValue
       	    */
           protected $id;

       	 /**
       	  * @var string
       	  * @ORMColumn(type="string")
       	  */
         protected $description;

           /**
            * @var DateTime
            * @ORMColumn(type="datetime")
            */                                           7
Purely Doctrine 2

     /**
      * @var DateTime
      * @ORMColumn(type="datetime")
      */
     protected $created;

     /**
      * @var ExampleUser
      * @ORMManyToOne(targetEntity="ExampleUser", inversedBy="assignedBugs")
      */
     protected $engineer;

     /**
      * @var DoctrineCommonCollectionsCollection<ExampleProduct>
      * @ORMManyToMany(targetEntity="ExampleProduct")
      */
     protected $products;
 }




                                                                                 8
Doctrine 2 in FLOW3

     /**
      * @var DateTime
      * @ORMColumn(type="datetime")
      */
     protected $created;

     /**
      * @var ExampleUser
      * @ORMManyToOne(targetEntity="ExampleUser", inversedBy="assignedBugs")
      */
     protected $engineer;

     /**
      * @var DoctrineCommonCollectionsCollection<ExampleProduct>
      * @ORMManyToMany(targetEntity="ExampleProduct")
      */
     protected $products;
 }




                                                                                 9
Using Repositories

Choose between the generic base repository to support any backend or
the Doctrine base repository to access advanced Doctrine functionality.


Extending the base repositories of FLOW3

 • Provides basic methods like:
   findAll(), countAll(), remove(), removeAll()

 • Provides automatic finder methods to retrieve by property:
   findByPropertyName($value), findOneByPropertyName($value)


Add specialized finder methods to your own repository.



                                                                          10
Advanced Queries using the QOM
PostRepository.php

class PostRepository extends FLOW3PersistenceRepository {

	   /**
	    * Finds most recent posts excluding the given post
	    *
	    * @param TYPO3BlogDomainModelPost $post Post to exclude from result
	    * @param integer $limit The number of posts to return at max
	    * @return array All posts of the $post's blog except for $post
	    */
	   public function findRecentExceptThis(TYPO3BlogDomainModelPost $post, $limit = 20) {
	   	 $query = $this->createQuery();
	   	 $posts = $query->matching($query->equals('blog', $post->getBlog()))
	   	 	 ->setOrderings(array(
             'date' => TYPO3FLOW3PersistenceQueryInterface::ORDER_DESCENDING
         ))
	   	 	 ->setLimit($limit)
	   	 	 ->execute()
	   	 	 ->toArray();

	   	   unset($posts[array_search($post, $posts)]);
	   	   return $posts;
	   }
}



                                                                                               11
Advanced Queries using DQL
PostRepository.php

class PostRepository extends FLOW3PersistenceDoctrineRepository {

	 /**
	   * Finds most recent posts excluding the given post
	   *
	   * @param TYPO3BlogDomainModelPost $post Post to exclude from result
	   * @param integer $limit The number of posts to return at max
	   * @return array All posts of the $post's blog except for $post
	   */
	 public function findRecentExceptThis(TYPO3BlogDomainModelPost $post, $limit = 20) {
	 	 	 // this is an alternative way of doing this when extending the Doctrine 2
	 	 	 // specific repository and using DQL.
	 	 $query = $this->entityManager->createQuery(
'SELECT p FROM TYPO3BlogDomainModelPost p WHERE p.blog = :blog AND NOT p
= :excludedPost ORDER BY p.date DESC'
);

	   	   return $query
	   	   	 ->setMaxResults($limit)
	   	   	 ->execute(array('blog' => $post->getBlog(), 'excludedPost' => $post));
	   }
}



                                                                                             12
Modeling Associations

• Modeling associations is hard for many people

• Start with the model, not the data



• Read the Doctrine documentation on associations

• Put a printed list of possible association on your wall

• Always remember:

  The owning side of a relationship determines the
    updates to the relationship in the database

                                                            13
Modeling Associations

How FLOW3 helps you with associations
• Cascade attributes are managed by FLOW3

 • based on aggregate boundaries

• Target entity can be left out

• Join columns and tables have automagic defaults

 • No, not only if your identifier column is named id

• Check your mapping with flow3 doctrine:validate

All magic can be overridden by using annotations!

                                                       14
Schema Management

Doctrine 2 Migrations
• Migrations allow schema versioning
  and change deployment

• Migrations are the recommended way
  for schema updates

• Can also be used to deploy predefined
  and update existing data

• Tools to create and deploy migrations
  are integrated with FLOW3


                                          15
Schema Management

Migrations Workflow
• Develop until your model is ready for a first “freeze”

• Create a migration and move / check / customize it

$ ./flow3 doctrine:migrationgenerate
Generated new migration class!

Next Steps:
- Move /…/DoctrineMigrations/Version20120328152041.php to YourPackage/Migrations/Mysql/
- Review and adjust the generated migration.
- (optional) execute the migration using ./flow3 doctrine:migrate




• Migrate to create the tables
$ ./flow3 doctrine:migrate




                                                                                          16
Schema Management
Migration files are usually very simple code


/**
 * Rename FLOW3 tables to follow FQCN
 */
class Version20110824124835 extends AbstractMigration {

	   /**
	    * @param Schema $schema
	    * @return void
	    */
	   public function up(Schema $schema) {
	   	 $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

	 	 $this->addSql("RENAME TABLE flow3_policy_role TO typo3_flow3_security_policy_role");
	 	 $this->addSql("RENAME TABLE flow3_resource_resource TO typo3_flow3_resource_resource");
	 	 $this->addSql("RENAME TABLE flow3_resource_resourcepointer TO
typo3_flow3_resource_resourcepointer");
	 	 $this->addSql("RENAME TABLE flow3_resource_securitypublishingconfiguration TO
typo3_flow3_security_authorization_resource_securitypublis_6180a");
	 	 $this->addSql("RENAME TABLE flow3_security_account TO typo3_flow3_security_account");
	 }




                                                                                              17
Schema Management
Checking the migration status on the console

$ ./flow3 doctrine:migrationstatus

 == Configuration
    >> Name:                   Doctrine Database Migrations
    >> Database Driver:        pdo_mysql
    >> Database Name:          blog
    >> Configuration Source:   manually configured
    >> Version Table Name:     flow3_doctrine_migrationstatus
    >> Migrations Namespace:   TYPO3FLOW3PersistenceDoctrineMigrations
    >> Migrations Directory:   /…/Configuration/Doctrine/Migrations
    >> Current Version:        2011-06-08 07:43:24 (20110608074324)
    >> Latest Version:         2011-06-08 07:43:24 (20110608074324)
    >> Executed Migrations:    1
    >> Available Migrations:   1
    >> New Migrations:         0

 == Migration Versions
    >> 2011-06-08 07:43:24 (20110608074324)          migrated



                                                                             18
Schema Management

Migrations Workflow
• Rinse and repeat: from now on create a new migration whenever
  you changed your model classes

• Generated migrations most probably need to be adjusted:

 • Renaming a model means renaming a table, not dropping and
   creating

 • Data migration might need to be added

 • Sometimes the generated changes are useless

           Good migrations make your user’s day

                                                                  19
Schema Management

Manual database updates
• For simple situations this can be good enough:

$ ./flow3 doctrine:create

$ ./flow3 doctrine:update


• Useful when

 • You need to use an existing database dump

 • No migrations exist for your database of choice (send patches!)

 • Using SQLite (due to limited schema change functionality)

                                                                     20
Integrating existing database tables

Use existing data from TYPO3 or other applications

Two principal approaches

 • Accessing raw data in a specialized repository

    • Use your own database connection and SQL

    • Does not use the default persistence layer

 • Creating a clean model mapped to the existing structure

    • FLOW3 will use the same database as the existing application

    • Uses the default persistence layer


                                                                     21
Mapping fe_users to a model

      /**
       * @FLOW3Entity
       * @ORMTable(name=”fe_users”)
       */
      class FrontendUser {

      	 /**
      	  * @var integer
      	  * @ORMId
      	  * @ORMColumn(name="uid")
      	  * @ORMGeneratedValue
      	  */
      	 protected $identifier;

      	 /**
      	  * @var string
      	  */
      	 protected $username;




                                       22
Mapping fe_users to a model

      	 /**
      	  * @var string
      	  */
      	 protected $username;

      	 /**
      	  * @var string
      	  * @ORMColumn(name="first_name")
      	  */
      	 protected $firstName;

      	 /**
      	  * @var DoctrineCommonCollectionsCollection<My
                                   ExampleFrontendUserGroup>
      	  * @ORMManyToMany(mappedBy="users")
      	  * @ORMJoinTable(name="user_groups_mm", …)
      	  */
      	 protected $groups;




                                                                 23
Integrating existing database tables

Pitfalls
 • Migrations will try to drop existing tables and columns!

 • Data type mismatches break FK constraints

   • integer vs. unsigned integer

 • Real data can be bad data

   • No FK constraints on legacy data

   • Missing entries break associations
 • Watch out for specifics like deleted and hidden flags

                                                              24
Persistence in FLOW3 with Doctrine 2




       Questions?
                                       25
Thank You!

 • These slides can be found at:
   http://speakerdeck.com/u/kdambekalns | http://slideshare.net/kfish

 • Give me feedback:
   karsten@typo3.org | karsten@dambekalns.de

 • Download FLOW3: http://flow3.typo3.org

 • Follow me on twitter: @kdambekalns



 • Support me using




                                                                       26

Más contenido relacionado

La actualidad más candente

Boost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
Boost Your Environment With XMLDB - UKOUG 2008 - Marco GralikeBoost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
Boost Your Environment With XMLDB - UKOUG 2008 - Marco GralikeMarco Gralike
 
Lab1-DB-Cassandra
Lab1-DB-CassandraLab1-DB-Cassandra
Lab1-DB-CassandraLilia Sfaxi
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On RailsJohn Wilker
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO ObjectsAJINKYA N
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With MysqlHarit Kothari
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaHermann Hueck
 
Store and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraStore and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraDeependra Ariyadewa
 
Michael Colon Portfolio
Michael Colon PortfolioMichael Colon Portfolio
Michael Colon Portfoliomichael_colon
 
Read, store and create xml and json
Read, store and create xml and jsonRead, store and create xml and json
Read, store and create xml and jsonKim Berg Hansen
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Kris Wallsmith
 

La actualidad más candente (20)

lab56_db
lab56_dblab56_db
lab56_db
 
Sql cheat sheet
Sql cheat sheetSql cheat sheet
Sql cheat sheet
 
laravel-53
laravel-53laravel-53
laravel-53
 
Lab2-DB-Mongodb
Lab2-DB-MongodbLab2-DB-Mongodb
Lab2-DB-Mongodb
 
Boost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
Boost Your Environment With XMLDB - UKOUG 2008 - Marco GralikeBoost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
Boost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
 
Lab1-DB-Cassandra
Lab1-DB-CassandraLab1-DB-Cassandra
Lab1-DB-Cassandra
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
 
Sqlite perl
Sqlite perlSqlite perl
Sqlite perl
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On Rails
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO Objects
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With Mysql
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
 
Store and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraStore and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and Cassandra
 
Save Repository From Save
Save Repository From SaveSave Repository From Save
Save Repository From Save
 
Michael Colon Portfolio
Michael Colon PortfolioMichael Colon Portfolio
Michael Colon Portfolio
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Read, store and create xml and json
Read, store and create xml and jsonRead, store and create xml and json
Read, store and create xml and json
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 

Destacado

March 6 building visibility for yr project
March 6 building visibility for yr projectMarch 6 building visibility for yr project
March 6 building visibility for yr projectHack the Hood
 
A Grandfather's Prayer
A Grandfather's PrayerA Grandfather's Prayer
A Grandfather's PrayerWilliam Wilkie
 
Module 3, 3.5 CRAP
Module 3, 3.5 CRAPModule 3, 3.5 CRAP
Module 3, 3.5 CRAPrboskett
 
Open Data 4 Startups
Open Data 4 StartupsOpen Data 4 Startups
Open Data 4 Startupsmzaglio
 
New co oct 8 2015 hth preso
New co oct 8 2015 hth  presoNew co oct 8 2015 hth  preso
New co oct 8 2015 hth presoHack the Hood
 
Digital Tv In Cee (2012)
Digital Tv In Cee (2012)Digital Tv In Cee (2012)
Digital Tv In Cee (2012)wimvermeulen
 
Feb 18 what we learned kcic
Feb 18  what we learned kcic Feb 18  what we learned kcic
Feb 18 what we learned kcic Hack the Hood
 
обезлесяването в българия
обезлесяването в българияобезлесяването в българия
обезлесяването в българияRositsa Dimova
 
TSP SYMPOSIUM Schneider, Henry.pptx
TSP SYMPOSIUM Schneider, Henry.pptxTSP SYMPOSIUM Schneider, Henry.pptx
TSP SYMPOSIUM Schneider, Henry.pptxHenry Schneider
 
Sept 20 2012 ona show me the numbers
Sept 20 2012 ona  show me the numbersSept 20 2012 ona  show me the numbers
Sept 20 2012 ona show me the numbersHack the Hood
 
Aug 15 show me the numbers
Aug 15  show me the numbersAug 15  show me the numbers
Aug 15 show me the numbersHack the Hood
 
Early spring in the park
Early spring in the parkEarly spring in the park
Early spring in the parkRositsa Dimova
 
P6.C Explaining Refraction
P6.C Explaining RefractionP6.C Explaining Refraction
P6.C Explaining Refractionpaulbhill
 
Orientation Sp08
Orientation Sp08Orientation Sp08
Orientation Sp08bigmac007
 
Agenda Setting For The Event G
Agenda Setting For The Event GAgenda Setting For The Event G
Agenda Setting For The Event Gguestd4ce70
 

Destacado (20)

Do italia sas samolet
Do italia sas samoletDo italia sas samolet
Do italia sas samolet
 
March 6 building visibility for yr project
March 6 building visibility for yr projectMarch 6 building visibility for yr project
March 6 building visibility for yr project
 
A Grandfather's Prayer
A Grandfather's PrayerA Grandfather's Prayer
A Grandfather's Prayer
 
Module 3, 3.5 CRAP
Module 3, 3.5 CRAPModule 3, 3.5 CRAP
Module 3, 3.5 CRAP
 
Open Data 4 Startups
Open Data 4 StartupsOpen Data 4 Startups
Open Data 4 Startups
 
New co oct 8 2015 hth preso
New co oct 8 2015 hth  presoNew co oct 8 2015 hth  preso
New co oct 8 2015 hth preso
 
Digital Tv In Cee (2012)
Digital Tv In Cee (2012)Digital Tv In Cee (2012)
Digital Tv In Cee (2012)
 
Feb 18 what we learned kcic
Feb 18  what we learned kcic Feb 18  what we learned kcic
Feb 18 what we learned kcic
 
обезлесяването в българия
обезлесяването в българияобезлесяването в българия
обезлесяването в българия
 
TSP SYMPOSIUM Schneider, Henry.pptx
TSP SYMPOSIUM Schneider, Henry.pptxTSP SYMPOSIUM Schneider, Henry.pptx
TSP SYMPOSIUM Schneider, Henry.pptx
 
Sept 20 2012 ona show me the numbers
Sept 20 2012 ona  show me the numbersSept 20 2012 ona  show me the numbers
Sept 20 2012 ona show me the numbers
 
Aug 15 show me the numbers
Aug 15  show me the numbersAug 15  show me the numbers
Aug 15 show me the numbers
 
Quen son eu? (I)
Quen son eu? (I)Quen son eu? (I)
Quen son eu? (I)
 
Early spring in the park
Early spring in the parkEarly spring in the park
Early spring in the park
 
P6.C Explaining Refraction
P6.C Explaining RefractionP6.C Explaining Refraction
P6.C Explaining Refraction
 
E twinningen
E twinningenE twinningen
E twinningen
 
Orientation Sp08
Orientation Sp08Orientation Sp08
Orientation Sp08
 
Agenda Setting For The Event G
Agenda Setting For The Event GAgenda Setting For The Event G
Agenda Setting For The Event G
 
Design Corps Web
Design Corps WebDesign Corps Web
Design Corps Web
 
Action
ActionAction
Action
 

Similar a Doctrine in FLOW3

Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0Robert Lemke
 
Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)Robert Lemke
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowKarsten Dambekalns
 
2012 08-11-flow3-northeast-php
2012 08-11-flow3-northeast-php2012 08-11-flow3-northeast-php
2012 08-11-flow3-northeast-phpJochen Rau
 
IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3Robert Lemke
 
IPCSE12: Hands on FLOW3
IPCSE12: Hands on FLOW3IPCSE12: Hands on FLOW3
IPCSE12: Hands on FLOW3Robert Lemke
 
Hands on FLOW3 (DPC12)
Hands on FLOW3 (DPC12)Hands on FLOW3 (DPC12)
Hands on FLOW3 (DPC12)Robert Lemke
 
Einführung in FLOW3/ Blog Package
Einführung in FLOW3/ Blog PackageEinführung in FLOW3/ Blog Package
Einführung in FLOW3/ Blog PackageMarkus Goldbeck
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkChristian Trabold
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumMatthias Noback
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaMatthias Noback
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014Matthias Noback
 
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...swentel
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionPhilip Norton
 
Getting Into FLOW3 (TYPO312CA)
Getting Into FLOW3 (TYPO312CA)Getting Into FLOW3 (TYPO312CA)
Getting Into FLOW3 (TYPO312CA)Robert Lemke
 
Applications for the Enterprise with PHP (CPEurope)
Applications for the Enterprise with PHP (CPEurope)Applications for the Enterprise with PHP (CPEurope)
Applications for the Enterprise with PHP (CPEurope)Robert Lemke
 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationJonathan Wage
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - TryoutMatthias Noback
 
TYPO3 6.2 for extension developer
TYPO3 6.2 for extension developerTYPO3 6.2 for extension developer
TYPO3 6.2 for extension developerNicole Cordes
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony AppsKris Wallsmith
 

Similar a Doctrine in FLOW3 (20)

Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0Fluent Development with FLOW3 1.0
Fluent Development with FLOW3 1.0
 
Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)Getting Into FLOW3 (DPC12)
Getting Into FLOW3 (DPC12)
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 Flow
 
2012 08-11-flow3-northeast-php
2012 08-11-flow3-northeast-php2012 08-11-flow3-northeast-php
2012 08-11-flow3-northeast-php
 
IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3IPCSE12: Getting into FLOW3
IPCSE12: Getting into FLOW3
 
IPCSE12: Hands on FLOW3
IPCSE12: Hands on FLOW3IPCSE12: Hands on FLOW3
IPCSE12: Hands on FLOW3
 
Hands on FLOW3 (DPC12)
Hands on FLOW3 (DPC12)Hands on FLOW3 (DPC12)
Hands on FLOW3 (DPC12)
 
Einführung in FLOW3/ Blog Package
Einführung in FLOW3/ Blog PackageEinführung in FLOW3/ Blog Package
Einführung in FLOW3/ Blog Package
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase framework
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup Belgium
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony Barcelona
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...
Drupal 8 configuration system for coders and site builders - DrupalCamp Balti...
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
 
Getting Into FLOW3 (TYPO312CA)
Getting Into FLOW3 (TYPO312CA)Getting Into FLOW3 (TYPO312CA)
Getting Into FLOW3 (TYPO312CA)
 
Applications for the Enterprise with PHP (CPEurope)
Applications for the Enterprise with PHP (CPEurope)Applications for the Enterprise with PHP (CPEurope)
Applications for the Enterprise with PHP (CPEurope)
 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 Integration
 
The Naked Bundle - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - Tryout
 
TYPO3 6.2 for extension developer
TYPO3 6.2 for extension developerTYPO3 6.2 for extension developer
TYPO3 6.2 for extension developer
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 

Más de Karsten Dambekalns

The Perfect Neos Project Setup
The Perfect Neos Project SetupThe Perfect Neos Project Setup
The Perfect Neos Project SetupKarsten Dambekalns
 
Sawubona! Content Dimensions with Neos
Sawubona! Content Dimensions with NeosSawubona! Content Dimensions with Neos
Sawubona! Content Dimensions with NeosKarsten Dambekalns
 
Deploying TYPO3 Neos websites using Surf
Deploying TYPO3 Neos websites using SurfDeploying TYPO3 Neos websites using Surf
Deploying TYPO3 Neos websites using SurfKarsten Dambekalns
 
Profiling TYPO3 Flow Applications
Profiling TYPO3 Flow ApplicationsProfiling TYPO3 Flow Applications
Profiling TYPO3 Flow ApplicationsKarsten Dambekalns
 
How Git and Gerrit make you more productive
How Git and Gerrit make you more productiveHow Git and Gerrit make you more productive
How Git and Gerrit make you more productiveKarsten Dambekalns
 
The agile future of a ponderous project
The agile future of a ponderous projectThe agile future of a ponderous project
The agile future of a ponderous projectKarsten Dambekalns
 
How Domain-Driven Design helps you to migrate into the future
How Domain-Driven Design helps you to migrate into the futureHow Domain-Driven Design helps you to migrate into the future
How Domain-Driven Design helps you to migrate into the futureKarsten Dambekalns
 
Content Repository, Versioning and Workspaces in TYPO3 Phoenix
Content Repository, Versioning and Workspaces in TYPO3 PhoenixContent Repository, Versioning and Workspaces in TYPO3 Phoenix
Content Repository, Versioning and Workspaces in TYPO3 PhoenixKarsten Dambekalns
 
Transparent Object Persistence (within FLOW3)
Transparent Object Persistence (within FLOW3)Transparent Object Persistence (within FLOW3)
Transparent Object Persistence (within FLOW3)Karsten Dambekalns
 
Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3Karsten Dambekalns
 
Implementing a JSR-283 Content Repository in PHP
Implementing a JSR-283 Content Repository in PHPImplementing a JSR-283 Content Repository in PHP
Implementing a JSR-283 Content Repository in PHPKarsten Dambekalns
 
Knowledge Management in der TYPO3 Community
Knowledge Management in der TYPO3 CommunityKnowledge Management in der TYPO3 Community
Knowledge Management in der TYPO3 CommunityKarsten Dambekalns
 
Implementing a JSR-283 Content Repository in PHP
Implementing a JSR-283 Content Repository in PHPImplementing a JSR-283 Content Repository in PHP
Implementing a JSR-283 Content Repository in PHPKarsten Dambekalns
 
A Content Repository for TYPO3 5.0
A Content Repository for TYPO3 5.0A Content Repository for TYPO3 5.0
A Content Repository for TYPO3 5.0Karsten Dambekalns
 
Introduction to Source Code Management
Introduction to Source Code ManagementIntroduction to Source Code Management
Introduction to Source Code ManagementKarsten Dambekalns
 

Más de Karsten Dambekalns (20)

The Perfect Neos Project Setup
The Perfect Neos Project SetupThe Perfect Neos Project Setup
The Perfect Neos Project Setup
 
Sawubona! Content Dimensions with Neos
Sawubona! Content Dimensions with NeosSawubona! Content Dimensions with Neos
Sawubona! Content Dimensions with Neos
 
Deploying TYPO3 Neos websites using Surf
Deploying TYPO3 Neos websites using SurfDeploying TYPO3 Neos websites using Surf
Deploying TYPO3 Neos websites using Surf
 
Profiling TYPO3 Flow Applications
Profiling TYPO3 Flow ApplicationsProfiling TYPO3 Flow Applications
Profiling TYPO3 Flow Applications
 
i18n and L10n in TYPO3 Flow
i18n and L10n in TYPO3 Flowi18n and L10n in TYPO3 Flow
i18n and L10n in TYPO3 Flow
 
FLOW3-Workshop F3X12
FLOW3-Workshop F3X12FLOW3-Workshop F3X12
FLOW3-Workshop F3X12
 
How Git and Gerrit make you more productive
How Git and Gerrit make you more productiveHow Git and Gerrit make you more productive
How Git and Gerrit make you more productive
 
The agile future of a ponderous project
The agile future of a ponderous projectThe agile future of a ponderous project
The agile future of a ponderous project
 
How Domain-Driven Design helps you to migrate into the future
How Domain-Driven Design helps you to migrate into the futureHow Domain-Driven Design helps you to migrate into the future
How Domain-Driven Design helps you to migrate into the future
 
Content Repository, Versioning and Workspaces in TYPO3 Phoenix
Content Repository, Versioning and Workspaces in TYPO3 PhoenixContent Repository, Versioning and Workspaces in TYPO3 Phoenix
Content Repository, Versioning and Workspaces in TYPO3 Phoenix
 
Transparent Object Persistence (within FLOW3)
Transparent Object Persistence (within FLOW3)Transparent Object Persistence (within FLOW3)
Transparent Object Persistence (within FLOW3)
 
JavaScript for PHP Developers
JavaScript for PHP DevelopersJavaScript for PHP Developers
JavaScript for PHP Developers
 
Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3
 
TDD (with FLOW3)
TDD (with FLOW3)TDD (with FLOW3)
TDD (with FLOW3)
 
Implementing a JSR-283 Content Repository in PHP
Implementing a JSR-283 Content Repository in PHPImplementing a JSR-283 Content Repository in PHP
Implementing a JSR-283 Content Repository in PHP
 
Knowledge Management in der TYPO3 Community
Knowledge Management in der TYPO3 CommunityKnowledge Management in der TYPO3 Community
Knowledge Management in der TYPO3 Community
 
Unicode & PHP6
Unicode & PHP6Unicode & PHP6
Unicode & PHP6
 
Implementing a JSR-283 Content Repository in PHP
Implementing a JSR-283 Content Repository in PHPImplementing a JSR-283 Content Repository in PHP
Implementing a JSR-283 Content Repository in PHP
 
A Content Repository for TYPO3 5.0
A Content Repository for TYPO3 5.0A Content Repository for TYPO3 5.0
A Content Repository for TYPO3 5.0
 
Introduction to Source Code Management
Introduction to Source Code ManagementIntroduction to Source Code Management
Introduction to Source Code Management
 

Último

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Último (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

Doctrine in FLOW3

  • 1. Karsten Dambekalns Persistence in FLOW3 with Doctrine 2 FLOW3 Experience 2012 1
  • 2. Karsten Dambekalns co-lead of TYPO3 5.0 and FLOW3 34 years old lives in Lübeck, Germany 1 wife, 3 sons, 1 espresso machine likes canoeing and climbing 2
  • 3. Persistence in FLOW3 with Doctrine 2 Object Persistence in the Flow • Based on Doctrine 2 • Seamless integration into FLOW3 • Provides the great Doctrine 2 features • Uses UUIDs • Our low-level persistence API • Allows for own, custom persistence backends (instead of Doctrine 2) • CouchDB is supported natively 3
  • 4. Basic Object Persistence • Get your repository injected conveniently • Handle your objects (almost) like you had no framework // Create a new customer and persist it: $customer = new Customer("Robert"); $this->customerRepository->add($customer); // Update a customer: $customer->setName("I, Robot"); $this->customerRepository->update($customer); // Find an existing customer: $otherCustomer = $this->customerRepository->findByFirstName("Karsten"); // … and delete it: $this->customerRepository->remove($otherCustomer); 4
  • 5. Persistence in FLOW3 with Doctrine 2 Differences to plain Doctrine 2 in modeling • Identifier properties are added transparently • FLOW3 does autodetection for • repository class names, column types, referenced column names • target entity types, cascade attributes • All Doctrine annotations work as usual • Whatever you specify wins over automation • Allows for full flexibility 5
  • 6. Purely Doctrine 2 use DoctrineORMMapping as ORM; /** * @ORMEntity(repositoryClass="BugRepository") */ class Bug { /** * @var integer * @ORMId * @ORMColumn(type="integer") * @ORMGeneratedValue */ protected $id; /** * @var string * @ORMColumn(type="string") */ protected $description; /** * @var DateTime * @ORMColumn(type="datetime") */ 6
  • 7. Doctrine 2 in FLOW3 use DoctrineORMMapping as ORM; /** * @ORMEntity(repositoryClass="BugRepository") */ class Bug { /** * @var integer * @ORMId * @ORMColumn(type="integer") * @ORMGeneratedValue */ protected $id; /** * @var string * @ORMColumn(type="string") */ protected $description; /** * @var DateTime * @ORMColumn(type="datetime") */ 7
  • 8. Purely Doctrine 2 /** * @var DateTime * @ORMColumn(type="datetime") */ protected $created; /** * @var ExampleUser * @ORMManyToOne(targetEntity="ExampleUser", inversedBy="assignedBugs") */ protected $engineer; /** * @var DoctrineCommonCollectionsCollection<ExampleProduct> * @ORMManyToMany(targetEntity="ExampleProduct") */ protected $products; } 8
  • 9. Doctrine 2 in FLOW3 /** * @var DateTime * @ORMColumn(type="datetime") */ protected $created; /** * @var ExampleUser * @ORMManyToOne(targetEntity="ExampleUser", inversedBy="assignedBugs") */ protected $engineer; /** * @var DoctrineCommonCollectionsCollection<ExampleProduct> * @ORMManyToMany(targetEntity="ExampleProduct") */ protected $products; } 9
  • 10. Using Repositories Choose between the generic base repository to support any backend or the Doctrine base repository to access advanced Doctrine functionality. Extending the base repositories of FLOW3 • Provides basic methods like: findAll(), countAll(), remove(), removeAll() • Provides automatic finder methods to retrieve by property: findByPropertyName($value), findOneByPropertyName($value) Add specialized finder methods to your own repository. 10
  • 11. Advanced Queries using the QOM PostRepository.php class PostRepository extends FLOW3PersistenceRepository { /** * Finds most recent posts excluding the given post * * @param TYPO3BlogDomainModelPost $post Post to exclude from result * @param integer $limit The number of posts to return at max * @return array All posts of the $post's blog except for $post */ public function findRecentExceptThis(TYPO3BlogDomainModelPost $post, $limit = 20) { $query = $this->createQuery(); $posts = $query->matching($query->equals('blog', $post->getBlog())) ->setOrderings(array( 'date' => TYPO3FLOW3PersistenceQueryInterface::ORDER_DESCENDING )) ->setLimit($limit) ->execute() ->toArray(); unset($posts[array_search($post, $posts)]); return $posts; } } 11
  • 12. Advanced Queries using DQL PostRepository.php class PostRepository extends FLOW3PersistenceDoctrineRepository { /** * Finds most recent posts excluding the given post * * @param TYPO3BlogDomainModelPost $post Post to exclude from result * @param integer $limit The number of posts to return at max * @return array All posts of the $post's blog except for $post */ public function findRecentExceptThis(TYPO3BlogDomainModelPost $post, $limit = 20) { // this is an alternative way of doing this when extending the Doctrine 2 // specific repository and using DQL. $query = $this->entityManager->createQuery( 'SELECT p FROM TYPO3BlogDomainModelPost p WHERE p.blog = :blog AND NOT p = :excludedPost ORDER BY p.date DESC' ); return $query ->setMaxResults($limit) ->execute(array('blog' => $post->getBlog(), 'excludedPost' => $post)); } } 12
  • 13. Modeling Associations • Modeling associations is hard for many people • Start with the model, not the data • Read the Doctrine documentation on associations • Put a printed list of possible association on your wall • Always remember: The owning side of a relationship determines the updates to the relationship in the database 13
  • 14. Modeling Associations How FLOW3 helps you with associations • Cascade attributes are managed by FLOW3 • based on aggregate boundaries • Target entity can be left out • Join columns and tables have automagic defaults • No, not only if your identifier column is named id • Check your mapping with flow3 doctrine:validate All magic can be overridden by using annotations! 14
  • 15. Schema Management Doctrine 2 Migrations • Migrations allow schema versioning and change deployment • Migrations are the recommended way for schema updates • Can also be used to deploy predefined and update existing data • Tools to create and deploy migrations are integrated with FLOW3 15
  • 16. Schema Management Migrations Workflow • Develop until your model is ready for a first “freeze” • Create a migration and move / check / customize it $ ./flow3 doctrine:migrationgenerate Generated new migration class! Next Steps: - Move /…/DoctrineMigrations/Version20120328152041.php to YourPackage/Migrations/Mysql/ - Review and adjust the generated migration. - (optional) execute the migration using ./flow3 doctrine:migrate • Migrate to create the tables $ ./flow3 doctrine:migrate 16
  • 17. Schema Management Migration files are usually very simple code /** * Rename FLOW3 tables to follow FQCN */ class Version20110824124835 extends AbstractMigration { /** * @param Schema $schema * @return void */ public function up(Schema $schema) { $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql"); $this->addSql("RENAME TABLE flow3_policy_role TO typo3_flow3_security_policy_role"); $this->addSql("RENAME TABLE flow3_resource_resource TO typo3_flow3_resource_resource"); $this->addSql("RENAME TABLE flow3_resource_resourcepointer TO typo3_flow3_resource_resourcepointer"); $this->addSql("RENAME TABLE flow3_resource_securitypublishingconfiguration TO typo3_flow3_security_authorization_resource_securitypublis_6180a"); $this->addSql("RENAME TABLE flow3_security_account TO typo3_flow3_security_account"); } 17
  • 18. Schema Management Checking the migration status on the console $ ./flow3 doctrine:migrationstatus == Configuration >> Name: Doctrine Database Migrations >> Database Driver: pdo_mysql >> Database Name: blog >> Configuration Source: manually configured >> Version Table Name: flow3_doctrine_migrationstatus >> Migrations Namespace: TYPO3FLOW3PersistenceDoctrineMigrations >> Migrations Directory: /…/Configuration/Doctrine/Migrations >> Current Version: 2011-06-08 07:43:24 (20110608074324) >> Latest Version: 2011-06-08 07:43:24 (20110608074324) >> Executed Migrations: 1 >> Available Migrations: 1 >> New Migrations: 0 == Migration Versions >> 2011-06-08 07:43:24 (20110608074324) migrated 18
  • 19. Schema Management Migrations Workflow • Rinse and repeat: from now on create a new migration whenever you changed your model classes • Generated migrations most probably need to be adjusted: • Renaming a model means renaming a table, not dropping and creating • Data migration might need to be added • Sometimes the generated changes are useless Good migrations make your user’s day 19
  • 20. Schema Management Manual database updates • For simple situations this can be good enough: $ ./flow3 doctrine:create $ ./flow3 doctrine:update • Useful when • You need to use an existing database dump • No migrations exist for your database of choice (send patches!) • Using SQLite (due to limited schema change functionality) 20
  • 21. Integrating existing database tables Use existing data from TYPO3 or other applications Two principal approaches • Accessing raw data in a specialized repository • Use your own database connection and SQL • Does not use the default persistence layer • Creating a clean model mapped to the existing structure • FLOW3 will use the same database as the existing application • Uses the default persistence layer 21
  • 22. Mapping fe_users to a model /** * @FLOW3Entity * @ORMTable(name=”fe_users”) */ class FrontendUser { /** * @var integer * @ORMId * @ORMColumn(name="uid") * @ORMGeneratedValue */ protected $identifier; /** * @var string */ protected $username; 22
  • 23. Mapping fe_users to a model /** * @var string */ protected $username; /** * @var string * @ORMColumn(name="first_name") */ protected $firstName; /** * @var DoctrineCommonCollectionsCollection<My ExampleFrontendUserGroup> * @ORMManyToMany(mappedBy="users") * @ORMJoinTable(name="user_groups_mm", …) */ protected $groups; 23
  • 24. Integrating existing database tables Pitfalls • Migrations will try to drop existing tables and columns! • Data type mismatches break FK constraints • integer vs. unsigned integer • Real data can be bad data • No FK constraints on legacy data • Missing entries break associations • Watch out for specifics like deleted and hidden flags 24
  • 25. Persistence in FLOW3 with Doctrine 2 Questions? 25
  • 26. Thank You! • These slides can be found at: http://speakerdeck.com/u/kdambekalns | http://slideshare.net/kfish • Give me feedback: karsten@typo3.org | karsten@dambekalns.de • Download FLOW3: http://flow3.typo3.org • Follow me on twitter: @kdambekalns • Support me using 26