SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Zend Framework meets Doctrine 2


Paul Seiffert I 24.11.11




                                  © Mayflower GmbH 2010
Paul Seiffert



                I Developer @ Mayflower seit
                    September 2010
                I PHP seit ca. 8 Jahren
                I Mobile Application Development


                I B.Sc. Computer Science (TU
                     München)
                I facebook.com/seiffertp



                                               Mayflower GmbH I 2
Agenda



1. Doctrine 2
   i. Übersicht
   ii. Architektur
   iii. Begriffe
2. Zend Framework Integration
3. Show Case




                                Mayflower GmbH I 3
Agenda



1. Doctrine 2
   i. Übersicht
   ii. Architektur
   iii. Begriffe
2. Zend Framework Integration
3. Show Case




                                Mayflower GmbH I 4
Doctrine



I PHP-ORM
    → geschrieben in PHP
    → geschrieben für PHP
I Mapping von Objekten der
  Business-Logik zu Datenbank-Records
I Mapping von Klassen der Business-Logik zu Datenbank-Tabellen
I API basiert auf Hibernate (Java)
I Repository- und Row-Data-Gateway-Pattern




                                                             Mayflower GmbH I 5
Doctrine 2




                                        2
I Komplette Neu-Entwicklung


I Im Vergleich zu Doctrine (1):
     → Weniger Magie
     → Um Welten performanter
     → Besseres Caching
     → Bessere Erweiterbarkeit
     → 100% PHP 5.3




                                  Mayflower GmbH I 6
Doctrine 2 - Architektur



                       Applikationen



                       ORM



                       DBAL

                                  Common
                                           Mayflower GmbH I 7
Doctrine 2 – Entities I



I Plain Old PHP Objects
I Vererbung
     → Single Table Inheritance
     → Class Table Inheritance
I Aggregation / Composition
    → Management von 1:1, 1:n und n:m Relationen




                                                   Mayflower GmbH I 8
Doctrine 2 – Entities II



namespace MyProjectEntity;

class User
{
    protected $_id;
    protected $_username;
    protected $_email;
                      Beispiel?
     public function getId()
     {
         return $this->_id;
     }

     ...
}



                                  Mayflower GmbH I 9
Doctrine 2 – EntityManager I



I Zentraler Zugriff auf die ORM-Funktionalität
     → Findet Entities
     → Persistiert Entities
     → Stellt Entity-Repositories zur Verfügung
I Aggregiert Änderungen und schreibt diese in Paketen (Unit of
  Work) zurück in die DB




                                                                 Mayflower GmbH I 10
Doctrine 2 – EntityManager II




 Entity 1
                        Entity
                                 DB
                       Manager
 Entity 2




                                      Mayflower GmbH I 11
Doctrine 2 – EntityManager III



// $em is the EntityManager

$peter = $em->find('MyProjectEntityUser', 5);

$peter->setEmail('peter@example.com');

$em->flush();


$paul = new User();
$paul->setUsername('Paul');
$paul->setEmail('paul@example.com');

$em->persist($paul);
$em->flush();



                                                   Mayflower GmbH I 12
Doctrine 2 – Repositories I



I Pro Entity-Klasse ein Repository
I API zur Suche nach Entities
     → find, findBy, findBy<attributeName>
     → eigene Such-Methoden
I spezielle Funktionalität durch
     Custom Repositories




                                             Mayflower GmbH I 13
Doctrine 2 – Repositories II




     Client
                  findMembersOfGroup(group)     User
                                              Repository

                              find(3)
find('User', 3)


               Entity
                                                     DB
              Manager



                                                           Mayflower GmbH I 14
Doctrine 2 – Repositories III



$repository = $em->getRepository('MyProjectEntityUser');

$peter = $repository->findOneBy(
                        array('username' => 'peter'));

$peter = $repository->findOneByUsername('peter');


$administrators = $repository->findBy(
                                   array('admin' => true));

$administrators = $repository->findByAdmin(true);




                                                      Mayflower GmbH I 15
Doctrine 2 – Metadata



I Mapping-Anweisungen (Metadaten) beschreiben
    → Die persistente Struktur der Daten
    → Die Beziehungen zwischen Klassen
I Metadaten können unterschiedlich vorliegen:
    → XML
    → YAML
    → PHP
    → DocBlock Annotations




                                                Mayflower GmbH I 16
Doctrine 2 – Metadata - XML



<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="..."
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="...">

  <entity name="MyProjectEntityUser" table="user">
     <id name="id" type="integer" column="id">
        <generator strategy="AUTO"/>
     </id>
     <field name="username" column="username" type="string"
            length="50" nullable="false" unique="true" />
     <field name="email" column="user_email" type="string"
            column-definition="CHAR(80) NOT NULL" />
  </entity>

</doctrine-mapping>


                                                      Mayflower GmbH I 17
Doctrine 2 – Metadata - YAML



MyProjectEntityUser:
  type: entity
  table: user
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    name:
      type: string
      length: 50
    email:
      type: string
      length: 80



                               Mayflower GmbH I 18
Doctrine 2 – Metadata – PHP



// MyProject/mapping/path/Entity/User

$metadata->mapField(
    array('id' => true,
          'fieldName' => 'id',
          'type' => 'integer'));

$metadata->mapField(
    array('fieldName' => 'username',
          'type' => 'string'));




                                        Mayflower GmbH I 19
Doctrine 2 – Metadata – DocBlock Annotations


/**
  * @Entity
  * @Table(name=“user“)
  */
class User
{
     /**
      * @Id @Column(type="integer", name=“id“)
      * @GeneratedValue
      */
     protected $_id;

    /** @Column(type="string", name=“username“) */
    protected $_username;

    /** @Column(type="string", name=“email“) */
    protected $_email;
}

                                                     Mayflower GmbH I 20
Doctrine 2 ...




 … es gibt noch so viel zu lernen!

I RTFM:
  http://www.doctrine-project.org/docs/orm/2.1/




                                                  Mayflower GmbH I 21
Agenda



1. Doctrine 2
   i. Übersicht
   ii. Architektur
   iii. Begriffe
2. Zend Framework Integration
3. Show Case




                                Mayflower GmbH I 22
Integration von Doctrine 2 in ZF-Projekte



I Doctrine 2 wird als fester Bestandteil von Symfony 2 entwickelt
I Doctrine 2 ist jünger als Zend Framework (1).
I Aktuell: ZF 1.11.11, Doctrine 2.1
I Doctrine 2 basiert auf PHP 5.3
    → Namespaces




                                                                    Mayflower GmbH I 23
Integration – Konfiguration der Classloader


use DoctrineCommonClassLoader as DoctrineClassLoader;

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    public function _initDoctrineClassLoader()
    {
        $classLoader = new DoctrineClassLoader('Doctrine');
        $classLoader->register();
        return $classLoader;
    }

    public function _initSymfonyClassLoader()
    {
        $classLoader = new DoctrineClassLoader('Symfony');
        $classLoader->register();
        return $classLoader;
    }
}

                                                      Mayflower GmbH I 24
Integration – Konfiguration mit Zend_Config



[production]
doctrine.connectionParameters.driver   = pdo_mysql
doctrine.connectionParameters.host     = localhost
doctrine.connectionParameters.user     = secret_username
doctrine.connectionParameters.password = secret_password
doctrine.connectionParameters.dbname   = dzf
doctrine.autoGenerateProxyClasses      = 0
doctrine.proxyPath                     =
                          APPLICATION_PATH "/models/Proxy"
doctrine.proxyNamespace                = Proxy
doctrine.entityPath                    =
                          APPLICATION_PATH "/models/Entity"
. . .

[development : production]
doctrine.autoGenerateProxyClasses       = 1
. . .

                                                      Mayflower GmbH I 25
Integration – Konfiguration des EntityManagers I


public function _initDoctrineEntityManager()
{
    $zendConfig = $this->getOptions();
    $connectionParameters =
        $zendConfig['doctrine']['connectionParameters'];

      $configuration = new DoctrineConfiguration();
      $configuration->setMetadataCacheImpl(
          $this->getResource('doctrineCache'));
      $configuration->setResultCacheImpl(
          $this->getResource('doctrineCache'));
      $configuration->setAutoGenerateProxyClasses(
          $zendConfig['doctrine']['autoGenerateProxyClasses']);
      $configuration->setProxyDir(
          $zendConfig['doctrine']['proxyPath']);
      $configuration->setProxyNamespace(
          $zendConfig['doctrine']['proxyNamespace']);
...

                                                        Mayflower GmbH I 26
Integration – Konfiguration des EntityManagers II


 ...
        $configuration->setMetadataDriverImpl(
            $configuration->newDefaultAnnotationDriver(
                $zendConfig['doctrine']['entityPath']));

       $eventManager = new DoctrineEventManager();

       $entityManager = DoctrineEntityManager::create(
                            $connectionParameters,
                            $configuration,
                            $eventManager);

       Zend_Registry::set('em', $entityManager);

       return $entityManager;
 }



                                                           Mayflower GmbH I 27
That's it!




             Mayflower GmbH I 28
CLI Tool

Doctrine Command Line Interface version 2.2.0-DEV

...
Available commands:


      That's it!
  help                             Displays help for a command
  list                             Lists commands
dbal
  dbal:import                      Import SQL file(s) directly to Database.
  dbal:run-sql                     Executes arbitrary SQL directly from the command line.
orm
  orm:clear-cache:metadata         Clear all metadata cache of the various cache drivers.
  orm:clear-cache:query            Clear all query cache of the various cache drivers.
  orm:clear-cache:result           Clear all result cache of the various cache drivers.
  orm:convert-d1-schema            Converts Doctrine 1.X schema into a Doctrine 2.X schema.
  orm:convert-mapping              Convert mapping information between supported formats.
  orm:ensure-production-settings   Verify that Doctrine is properly configured for a production environment.
  orm:generate-entities            Generate entity classes and method stubs from your mapping information.
  orm:generate-proxies             Generates proxy classes for entity classes.
  orm:generate-repositories        Generate repository classes from your mapping information.
  orm:info                         Show basic information about all mapped entities
  orm:run-dql                      Executes arbitrary DQL directly from the command line.
  orm:schema-tool:create           Processes the schema and either create it directly on EntityManager
Storage Connection or generate the SQL output.
  orm:schema-tool:drop             Drop the complete database schema of EntityManager Storage Connection or
generate the corresponding SQL output.
  orm:schema-tool:update           Executes (or dumps) the SQL needed to update the database schema to match
the current mapping metadata.
  orm:validate-schema              Validate the mapping files.




                                                                                               Mayflower GmbH I 29
Integration – CLI



I Bootstrap von ZF-Applikation notwendig!
    → Anpassung des Standard Doctrine-CLI-Scripts


 // Erstellen der Zend_Application und Bootstrapping

 /**
  * @var DoctrineORMEntityManager $entityManager
  */
 $entityManager = Zend_Registry::get('em');
 $helperSet = new SymfonyComponentConsoleHelperHelperSet(
   array('db' => new DoctrineDBALToolsConsoleHelperConnectionHelper(
                        $entityManager->getConnection()),
         'em' => new DoctrineORMToolsConsoleHelperEntityManagerHelper(
                        $entityManager)));
 DoctrineORMToolsConsoleConsoleRunner::run($helperSet);




                                                                    Mayflower GmbH I 30
Agenda



1. Doctrine 2
   i. Übersicht
   ii. Architektur
   iii. Begriffe
2. Zend Framework Integration
3. Show Case




                                Mayflower GmbH I 31
Vielen Dank für Eure Aufmerksamkeit!




      Referent   Paul Seiffert
                 Paul.Seiffert@mayflower.de
                 +49 89 242054 1172
                 Mayflower GmbH
                 Mannhardtstrasse6
                 80538 München


19.12.11                                Mayflower GmbH   32
Literatur


I Doctrine 2 Documentation
  http://www.doctrine-project.org/docs/orm/2.1/en/
I Vortrag „Doctrine 2 – Not the same Old PHP ORM“ von Jonathan H.
  Wage




                                                           Mayflower GmbH I 33

Weitere ähnliche Inhalte

Was ist angesagt?

HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Vaadin7 modern-web-apps-in-java
Vaadin7 modern-web-apps-in-javaVaadin7 modern-web-apps-in-java
Vaadin7 modern-web-apps-in-java
Joonas Lehtinen
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
Kim Hunmin
 

Was ist angesagt? (20)

Phactory
PhactoryPhactory
Phactory
 
Architecting for PHP5 - Why "Runs on PHP5" is not "Written for PHP5"
Architecting for PHP5 - Why "Runs on PHP5" is not "Written for PHP5"Architecting for PHP5 - Why "Runs on PHP5" is not "Written for PHP5"
Architecting for PHP5 - Why "Runs on PHP5" is not "Written for PHP5"
 
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
Fnt Software Solutions Pvt Ltd Placement Papers - PHP TechnologyFnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
Fnt Software Solutions Pvt Ltd Placement Papers - PHP Technology
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Swing database(mysql)
Swing database(mysql)Swing database(mysql)
Swing database(mysql)
 
Libertyvasion2010
Libertyvasion2010Libertyvasion2010
Libertyvasion2010
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Symfony 2.0
Symfony 2.0Symfony 2.0
Symfony 2.0
 
Vaadin 7
Vaadin 7Vaadin 7
Vaadin 7
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Drupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageDrupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of Usage
 
Sequelize
SequelizeSequelize
Sequelize
 
Intro programacion funcional
Intro programacion funcionalIntro programacion funcional
Intro programacion funcional
 
Vaadin7 modern-web-apps-in-java
Vaadin7 modern-web-apps-in-javaVaadin7 modern-web-apps-in-java
Vaadin7 modern-web-apps-in-java
 
Lexical environment in ecma 262 5
Lexical environment in ecma 262 5Lexical environment in ecma 262 5
Lexical environment in ecma 262 5
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in Laravel
 
Python Part 2
Python Part 2Python Part 2
Python Part 2
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Creating Ext JS Extensions and Components
Creating Ext JS Extensions and ComponentsCreating Ext JS Extensions and Components
Creating Ext JS Extensions and Components
 

Ähnlich wie Zend Framework meets Doctrine 2

Ähnlich wie Zend Framework meets Doctrine 2 (20)

De constructed-module
De constructed-moduleDe constructed-module
De constructed-module
 
Oops in php
Oops in phpOops in php
Oops in php
 
Introduction Php
Introduction PhpIntroduction Php
Introduction Php
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHP
 
Symfony internals [english]
Symfony internals [english]Symfony internals [english]
Symfony internals [english]
 
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)New Symfony Tips & Tricks (SymfonyCon Paris 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
 
Utilization of zend an ultimate alternate for intense data processing
Utilization of zend  an ultimate alternate for intense data processingUtilization of zend  an ultimate alternate for intense data processing
Utilization of zend an ultimate alternate for intense data processing
 
Working With The Symfony Admin Generator
Working With The Symfony Admin GeneratorWorking With The Symfony Admin Generator
Working With The Symfony Admin Generator
 
Yii - Next level PHP Framework von Florian Facker
Yii - Next level PHP Framework von Florian FackerYii - Next level PHP Framework von Florian Facker
Yii - Next level PHP Framework von Florian Facker
 
Yii Next Level
Yii Next LevelYii Next Level
Yii Next Level
 
Lecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptxLecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptx
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
 
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 - Tryout
The Naked Bundle - TryoutThe Naked Bundle - Tryout
The Naked Bundle - Tryout
 
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
 
Part 2
Part 2Part 2
Part 2
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Drupal 8: Entities
Drupal 8: EntitiesDrupal 8: Entities
Drupal 8: Entities
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
fb-researchの舞台裏No.2~技術編~(HatchUp主催 渋谷Facebookアプリ勉強会)
fb-researchの舞台裏No.2~技術編~(HatchUp主催 渋谷Facebookアプリ勉強会)fb-researchの舞台裏No.2~技術編~(HatchUp主催 渋谷Facebookアプリ勉強会)
fb-researchの舞台裏No.2~技術編~(HatchUp主催 渋谷Facebookアプリ勉強会)
 

Mehr von Mayflower GmbH

Plugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debuggingPlugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debugging
Mayflower GmbH
 

Mehr von Mayflower GmbH (20)

Mit Maintenance umgehen können- Fixt du noch Bugs oder lieferst du schon neue...
Mit Maintenance umgehen können- Fixt du noch Bugs oder lieferst du schon neue...Mit Maintenance umgehen können- Fixt du noch Bugs oder lieferst du schon neue...
Mit Maintenance umgehen können- Fixt du noch Bugs oder lieferst du schon neue...
 
Why and what is go
Why and what is goWhy and what is go
Why and what is go
 
Agile Anti-Patterns
Agile Anti-PatternsAgile Anti-Patterns
Agile Anti-Patterns
 
JavaScript Days 2015: Security
JavaScript Days 2015: SecurityJavaScript Days 2015: Security
JavaScript Days 2015: Security
 
Vom Entwickler zur Führungskraft
Vom Entwickler zur FührungskraftVom Entwickler zur Führungskraft
Vom Entwickler zur Führungskraft
 
Produktive teams
Produktive teamsProduktive teams
Produktive teams
 
Salt and pepper — native code in the browser Browser using Google native Client
Salt and pepper — native code in the browser Browser using Google native ClientSalt and pepper — native code in the browser Browser using Google native Client
Salt and pepper — native code in the browser Browser using Google native Client
 
Plugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debuggingPlugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debugging
 
Usability im web
Usability im webUsability im web
Usability im web
 
Rewrites überleben
Rewrites überlebenRewrites überleben
Rewrites überleben
 
JavaScript Security
JavaScript SecurityJavaScript Security
JavaScript Security
 
50 mal produktiver - oder warum ich gute Teams brauche und nicht gute Entwick...
50 mal produktiver - oder warum ich gute Teams brauche und nicht gute Entwick...50 mal produktiver - oder warum ich gute Teams brauche und nicht gute Entwick...
50 mal produktiver - oder warum ich gute Teams brauche und nicht gute Entwick...
 
Responsive Webdesign
Responsive WebdesignResponsive Webdesign
Responsive Webdesign
 
Native Cross-Platform-Apps mit Titanium Mobile und Alloy
Native Cross-Platform-Apps mit Titanium Mobile und AlloyNative Cross-Platform-Apps mit Titanium Mobile und Alloy
Native Cross-Platform-Apps mit Titanium Mobile und Alloy
 
Pair Programming Mythbusters
Pair Programming MythbustersPair Programming Mythbusters
Pair Programming Mythbusters
 
Shoeism - Frau im Glück
Shoeism - Frau im GlückShoeism - Frau im Glück
Shoeism - Frau im Glück
 
Bessere Software schneller liefern
Bessere Software schneller liefernBessere Software schneller liefern
Bessere Software schneller liefern
 
Von 0 auf 100 in 2 Sprints
Von 0 auf 100 in 2 SprintsVon 0 auf 100 in 2 Sprints
Von 0 auf 100 in 2 Sprints
 
Piwik anpassen und skalieren
Piwik anpassen und skalierenPiwik anpassen und skalieren
Piwik anpassen und skalieren
 
Agilitaet im E-Commerce - E-Commerce Breakfast
Agilitaet im E-Commerce - E-Commerce BreakfastAgilitaet im E-Commerce - E-Commerce Breakfast
Agilitaet im E-Commerce - E-Commerce Breakfast
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

Zend Framework meets Doctrine 2

  • 1. Zend Framework meets Doctrine 2 Paul Seiffert I 24.11.11 © Mayflower GmbH 2010
  • 2. Paul Seiffert I Developer @ Mayflower seit September 2010 I PHP seit ca. 8 Jahren I Mobile Application Development I B.Sc. Computer Science (TU München) I facebook.com/seiffertp Mayflower GmbH I 2
  • 3. Agenda 1. Doctrine 2 i. Übersicht ii. Architektur iii. Begriffe 2. Zend Framework Integration 3. Show Case Mayflower GmbH I 3
  • 4. Agenda 1. Doctrine 2 i. Übersicht ii. Architektur iii. Begriffe 2. Zend Framework Integration 3. Show Case Mayflower GmbH I 4
  • 5. Doctrine I PHP-ORM → geschrieben in PHP → geschrieben für PHP I Mapping von Objekten der Business-Logik zu Datenbank-Records I Mapping von Klassen der Business-Logik zu Datenbank-Tabellen I API basiert auf Hibernate (Java) I Repository- und Row-Data-Gateway-Pattern Mayflower GmbH I 5
  • 6. Doctrine 2 2 I Komplette Neu-Entwicklung I Im Vergleich zu Doctrine (1): → Weniger Magie → Um Welten performanter → Besseres Caching → Bessere Erweiterbarkeit → 100% PHP 5.3 Mayflower GmbH I 6
  • 7. Doctrine 2 - Architektur Applikationen ORM DBAL Common Mayflower GmbH I 7
  • 8. Doctrine 2 – Entities I I Plain Old PHP Objects I Vererbung → Single Table Inheritance → Class Table Inheritance I Aggregation / Composition → Management von 1:1, 1:n und n:m Relationen Mayflower GmbH I 8
  • 9. Doctrine 2 – Entities II namespace MyProjectEntity; class User { protected $_id; protected $_username; protected $_email; Beispiel? public function getId() { return $this->_id; } ... } Mayflower GmbH I 9
  • 10. Doctrine 2 – EntityManager I I Zentraler Zugriff auf die ORM-Funktionalität → Findet Entities → Persistiert Entities → Stellt Entity-Repositories zur Verfügung I Aggregiert Änderungen und schreibt diese in Paketen (Unit of Work) zurück in die DB Mayflower GmbH I 10
  • 11. Doctrine 2 – EntityManager II Entity 1 Entity DB Manager Entity 2 Mayflower GmbH I 11
  • 12. Doctrine 2 – EntityManager III // $em is the EntityManager $peter = $em->find('MyProjectEntityUser', 5); $peter->setEmail('peter@example.com'); $em->flush(); $paul = new User(); $paul->setUsername('Paul'); $paul->setEmail('paul@example.com'); $em->persist($paul); $em->flush(); Mayflower GmbH I 12
  • 13. Doctrine 2 – Repositories I I Pro Entity-Klasse ein Repository I API zur Suche nach Entities → find, findBy, findBy<attributeName> → eigene Such-Methoden I spezielle Funktionalität durch Custom Repositories Mayflower GmbH I 13
  • 14. Doctrine 2 – Repositories II Client findMembersOfGroup(group) User Repository find(3) find('User', 3) Entity DB Manager Mayflower GmbH I 14
  • 15. Doctrine 2 – Repositories III $repository = $em->getRepository('MyProjectEntityUser'); $peter = $repository->findOneBy( array('username' => 'peter')); $peter = $repository->findOneByUsername('peter'); $administrators = $repository->findBy( array('admin' => true)); $administrators = $repository->findByAdmin(true); Mayflower GmbH I 15
  • 16. Doctrine 2 – Metadata I Mapping-Anweisungen (Metadaten) beschreiben → Die persistente Struktur der Daten → Die Beziehungen zwischen Klassen I Metadaten können unterschiedlich vorliegen: → XML → YAML → PHP → DocBlock Annotations Mayflower GmbH I 16
  • 17. Doctrine 2 – Metadata - XML <?xml version="1.0" encoding="UTF-8"?> <doctrine-mapping xmlns="..." xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="..."> <entity name="MyProjectEntityUser" table="user"> <id name="id" type="integer" column="id"> <generator strategy="AUTO"/> </id> <field name="username" column="username" type="string" length="50" nullable="false" unique="true" /> <field name="email" column="user_email" type="string" column-definition="CHAR(80) NOT NULL" /> </entity> </doctrine-mapping> Mayflower GmbH I 17
  • 18. Doctrine 2 – Metadata - YAML MyProjectEntityUser: type: entity table: user id: id: type: integer generator: strategy: AUTO fields: name: type: string length: 50 email: type: string length: 80 Mayflower GmbH I 18
  • 19. Doctrine 2 – Metadata – PHP // MyProject/mapping/path/Entity/User $metadata->mapField( array('id' => true, 'fieldName' => 'id', 'type' => 'integer')); $metadata->mapField( array('fieldName' => 'username', 'type' => 'string')); Mayflower GmbH I 19
  • 20. Doctrine 2 – Metadata – DocBlock Annotations /** * @Entity * @Table(name=“user“) */ class User { /** * @Id @Column(type="integer", name=“id“) * @GeneratedValue */ protected $_id; /** @Column(type="string", name=“username“) */ protected $_username; /** @Column(type="string", name=“email“) */ protected $_email; } Mayflower GmbH I 20
  • 21. Doctrine 2 ... … es gibt noch so viel zu lernen! I RTFM: http://www.doctrine-project.org/docs/orm/2.1/ Mayflower GmbH I 21
  • 22. Agenda 1. Doctrine 2 i. Übersicht ii. Architektur iii. Begriffe 2. Zend Framework Integration 3. Show Case Mayflower GmbH I 22
  • 23. Integration von Doctrine 2 in ZF-Projekte I Doctrine 2 wird als fester Bestandteil von Symfony 2 entwickelt I Doctrine 2 ist jünger als Zend Framework (1). I Aktuell: ZF 1.11.11, Doctrine 2.1 I Doctrine 2 basiert auf PHP 5.3 → Namespaces Mayflower GmbH I 23
  • 24. Integration – Konfiguration der Classloader use DoctrineCommonClassLoader as DoctrineClassLoader; class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { public function _initDoctrineClassLoader() { $classLoader = new DoctrineClassLoader('Doctrine'); $classLoader->register(); return $classLoader; } public function _initSymfonyClassLoader() { $classLoader = new DoctrineClassLoader('Symfony'); $classLoader->register(); return $classLoader; } } Mayflower GmbH I 24
  • 25. Integration – Konfiguration mit Zend_Config [production] doctrine.connectionParameters.driver = pdo_mysql doctrine.connectionParameters.host = localhost doctrine.connectionParameters.user = secret_username doctrine.connectionParameters.password = secret_password doctrine.connectionParameters.dbname = dzf doctrine.autoGenerateProxyClasses = 0 doctrine.proxyPath = APPLICATION_PATH "/models/Proxy" doctrine.proxyNamespace = Proxy doctrine.entityPath = APPLICATION_PATH "/models/Entity" . . . [development : production] doctrine.autoGenerateProxyClasses = 1 . . . Mayflower GmbH I 25
  • 26. Integration – Konfiguration des EntityManagers I public function _initDoctrineEntityManager() { $zendConfig = $this->getOptions(); $connectionParameters = $zendConfig['doctrine']['connectionParameters']; $configuration = new DoctrineConfiguration(); $configuration->setMetadataCacheImpl( $this->getResource('doctrineCache')); $configuration->setResultCacheImpl( $this->getResource('doctrineCache')); $configuration->setAutoGenerateProxyClasses( $zendConfig['doctrine']['autoGenerateProxyClasses']); $configuration->setProxyDir( $zendConfig['doctrine']['proxyPath']); $configuration->setProxyNamespace( $zendConfig['doctrine']['proxyNamespace']); ... Mayflower GmbH I 26
  • 27. Integration – Konfiguration des EntityManagers II ... $configuration->setMetadataDriverImpl( $configuration->newDefaultAnnotationDriver( $zendConfig['doctrine']['entityPath'])); $eventManager = new DoctrineEventManager(); $entityManager = DoctrineEntityManager::create( $connectionParameters, $configuration, $eventManager); Zend_Registry::set('em', $entityManager); return $entityManager; } Mayflower GmbH I 27
  • 28. That's it! Mayflower GmbH I 28
  • 29. CLI Tool Doctrine Command Line Interface version 2.2.0-DEV ... Available commands: That's it! help Displays help for a command list Lists commands dbal dbal:import Import SQL file(s) directly to Database. dbal:run-sql Executes arbitrary SQL directly from the command line. orm orm:clear-cache:metadata Clear all metadata cache of the various cache drivers. orm:clear-cache:query Clear all query cache of the various cache drivers. orm:clear-cache:result Clear all result cache of the various cache drivers. orm:convert-d1-schema Converts Doctrine 1.X schema into a Doctrine 2.X schema. orm:convert-mapping Convert mapping information between supported formats. orm:ensure-production-settings Verify that Doctrine is properly configured for a production environment. orm:generate-entities Generate entity classes and method stubs from your mapping information. orm:generate-proxies Generates proxy classes for entity classes. orm:generate-repositories Generate repository classes from your mapping information. orm:info Show basic information about all mapped entities orm:run-dql Executes arbitrary DQL directly from the command line. orm:schema-tool:create Processes the schema and either create it directly on EntityManager Storage Connection or generate the SQL output. orm:schema-tool:drop Drop the complete database schema of EntityManager Storage Connection or generate the corresponding SQL output. orm:schema-tool:update Executes (or dumps) the SQL needed to update the database schema to match the current mapping metadata. orm:validate-schema Validate the mapping files. Mayflower GmbH I 29
  • 30. Integration – CLI I Bootstrap von ZF-Applikation notwendig! → Anpassung des Standard Doctrine-CLI-Scripts // Erstellen der Zend_Application und Bootstrapping /** * @var DoctrineORMEntityManager $entityManager */ $entityManager = Zend_Registry::get('em'); $helperSet = new SymfonyComponentConsoleHelperHelperSet( array('db' => new DoctrineDBALToolsConsoleHelperConnectionHelper( $entityManager->getConnection()), 'em' => new DoctrineORMToolsConsoleHelperEntityManagerHelper( $entityManager))); DoctrineORMToolsConsoleConsoleRunner::run($helperSet); Mayflower GmbH I 30
  • 31. Agenda 1. Doctrine 2 i. Übersicht ii. Architektur iii. Begriffe 2. Zend Framework Integration 3. Show Case Mayflower GmbH I 31
  • 32. Vielen Dank für Eure Aufmerksamkeit! Referent Paul Seiffert Paul.Seiffert@mayflower.de +49 89 242054 1172 Mayflower GmbH Mannhardtstrasse6 80538 München 19.12.11 Mayflower GmbH 32
  • 33. Literatur I Doctrine 2 Documentation http://www.doctrine-project.org/docs/orm/2.1/en/ I Vortrag „Doctrine 2 – Not the same Old PHP ORM“ von Jonathan H. Wage Mayflower GmbH I 33