SlideShare una empresa de Scribd logo
1 de 55
Zend Framework and Doctrine Putting the M in Zend
A Few Notes… On the presentation: For the so inclined, the “model object” referred to is equivalent to the DDD domain object (I think). On Me: Isaac Foster Zend Framework Certified Currently working for Tabula Digita.
Your Honor, I Intend to Prove… That Doctrine’s value added over Zend_Dbis the framework it provides for business logic. Other features make it a complete, powerful tool.
First TLA: MVC Model – Behavior and data of the application. View– Display information. Controller– Takes inputs 	 from the user, invokes the  	model and chooses the view.
The M in MVC Model objects hold business data and logic. Model != DB: True, data that a model acts on is often persisted in a db. Db code in the model layer, not necessarily model object. Model object should focus on what makes it special.  			your models -->
Separate Business and Persistence Logic DBAL (Database Abstraction Layer) One API to rule them all. ORM (Object Relational Mapper) Put the object in, get the object out. ↑Consistency, ↑Reliability, ↑Reuse, ↑Ease… It’s a Good Thing Snoop shares his 			thoughts on the active 			record pattern.
Frameworks and Libraries Help us Achieve These (and other) Goals and one of those frameworks is…
Zend Framework ,[object Object]
Great View and Controller framework:
IOC lets you focus on the ACTION, not the request, response, router, dispatcher …Components ,[object Object]
Zend_Auth for authentication
Zend_Session for session management… what about M?
The M in Z-E-N-D? Zend_Db wraps db driver for DBAL.  Zend_Db_Table wraps a table, gives some structure to a model, ORM-ish. Zend_DB_Table_Row wraps row, active record features.
The M in Z-E-N-D? Provides: Protection from SQL Injection Query Construction API Transactions Profiler Cache
So What’s the Problem? Definitely Zend_Db, not Zend_Model Not much from a business logic perspective: Little help you stay DRY with business logic. Not much in the way of model life-cycle hooks (preSave, postSave, preDelete, etc). Still thinking about db’s, tables, and table references, not models and relationships.
Doctrine is…DBAL + ORM + Active Record + Model Framework Provides framework for business logic… Plugins hook into events, core code untouched. Reuse code and structure with behaviors. Configure validation and rules. Doctrine model IOC ≈ ZF controllers IOC Think more about models, not tables.
Doctrine Will create your database tables. Migration tools. Performance tools and configurations. Utilities Command line interface Pagination
Let’s Take It For a Spin
A Problem To Solve… Need to keep track of Users Auto incremented id. Email property must be valid email address. Password must be hashed. Want to send a confirmation email to new users after they register.
A Doctrine Solution
A Harder Problem… Exercise 1st Amendment right to blog Need to update blog post, track previous versions. Want to attach images to a post. Store them on Amazon S3 Update author’s numPosts field after blogging. Don’t feel like creating tables manually.
A Doctrine Solution
Doctrine Basics
Guideposts Doctrine_Connection ≈ Zend_Db Doctrine_Table ≈ Zend_Db_Table_Abstract Doctrine_Record ≈ Zend_Db_Table_Row_Abstract
Doctrine Core Classes Doctrine_Manager Manages connections, knows available drivers. Handles application wide options. Doctrine_Core Manages autoloading. Methods to create tables, export database, etc.
Connections Connect to a database: MySql, MsSql, Oracle, Postgre, DB2, Sqlite.
Bootstrapping Connections and autoloading in bootstrap. Doctrine autoloader for models. Zend Autoloader for Doctrine library files.
Defining Models: Goal Model creation should be like Lego building. Configure when possible, code if necessary. Let framework do the easy stuff. Leverage framework for harder stuff.
Defining Models Each model has a Doctrine_Table. Structure and meta-info stored there. setTableDefinition and setUp create the table: hasColumn -> add properties  hasOne -> add one-to-one relationships hasMany -> add one-to-many and many-to-many Model can be defined in code or YAML config.
A More Detailed Problem… Need a Blog model with: Unique integer key. Title (non null, less than 150 chars) Text (non null). Flag for whether it is published (default false). Foreign key for relating to the author. DETAILS, REQUIREMENTS, RULES!! WHAT TO DO!!
Defining Models: Properties
Doctrine_Record::hasColumn() Adds properties to your model. Blog has a title property, content property, etc. hasColumn($name, $type [,$length,  $options]) name – “propertyName” or “columnName as propertyName” type - int, string, boolean, float, many more. length – max length options – options
Property Options default – sets default value. primary –  if the primary key. autoincrement – if autoincrementing id. notnull – enforce the value not be null. email – enforce the value be a valid email. Other validator indicators
More Details… Blog also needs: An Author. Images attached to it for upload and display. WHAT TO DO!!
Defining Models: Relationships
Doctrine_Record ::hasOne() Defines one-to-one associations between your model and another. hasOne($associationClass [, $options]) associationClass –either “associationClass” or “associationClass as associationName” options – the association options
Doctrine_Record::hasMany() Add one-to-many, many-to-many associations. A Blog has Comments (1-to-many). A User can be in many Groups and a Group can have many Users (many-to-many). hasMany($associationClass [, $options]) name – “associationClass” or “associationClass as associationName” options – association options
More Problem Specs… When… The blog is created: An email should be sent to all editors informing them they need to proof read it. The blog is published: An email should be sent to the mailing list informing them of the new post. A Facebook story should be published doing the same. A Tweet should be sent with the fist 140 characters. The blog is saved (inserted or updated). All image objects associated with it must be uploaded to Amazon S3
Note That… Stuff happens when other stuff happens. On X, do Y. Not Blog’s responsibility to email, Facebook, Tweet, or upload to S3. Probably shouldn’t be hardcoded into Blog class. COMPLEXITY!! AND YOU WANT ARCHITECTURAL PURITY!!!  	LAAAAMMMEE!!!
Plugins (Listeners) As Zendfront controller pluginshook into preDispatch, postDispatch, etc, events… …so Doctrine record pluginshook into: pre/post Insert/Update/Save/Delete, others. Also plugins for connections. Hook into: pre/post connect/transactionBeing/fetch/exec, others.
Plugins (Listeners) IOC: add logic to a model or connection without touching the core code. Log and profile all SQL queries (connection hooks). Send an email to a user when they sign up (model hooks). Register as many as you need. Similar to JS DOM events.
Step One: Create the Plugins
Step Two: Add the Plugins
Doctrine_Record::addListener() Add a plugin to run when something happens. addListener($listener, $listenerName = null) listener  the plugin to add. listenerName  name of the plugin, useful for removing later.
More Problem Specs… The Blog must… Keep track of when it was created and last updated. Timestamps should be set automatically, not explicitly by consumer code. Keep track of previous versions. Provide revert and get versions methods. Versioning happens automatically, not in consumer code. Be flaggable. Provide a flag method. Automatically increment the Blog’s flag count.
Notice That… These behaviors are generic: Probably want them elsewhere, but in different combinations, with different configurations. Implementation not special to Blog. Define base classes for each and extend… …But no multiple inheritance in PHP. I’VE HAD ALL I CAN STANDS, AND I CAN’T STANDS NO MORE!
Mix-in With Templates Avoid single inheritance issues.  Don’t choose between extending Flaggable, Taggable, Locateable, Versionable, just mix-in all of them! Stay DRY. Inversion of (model definition) control. Add properties, relationships, plugins,… and methods! Encapsulate generic behavior in one place. Add as many as you want.
Defining Models: BehaviorsStep One: Find a Template… In “path/to/Doctrine/Template” Community contributed at http://trac.doctrine-project.org/browser/extensions?rev=7461
Defining Models: Behaviors…or Make Your Own
Defining Models: BehaviorsStep Two: Tell Your Model to “actAs” the Template
Doctrine_Record::actAs() Adds a template to your model. actAs($template[, $options]) $template – template name or instance. $options – configuration options
Defining Models: Summary Model creation should be like Lego building. Snap on properties and relationships. Snap in listeners that get called at hook points. Snap on behavior with templates.
Querying Models Query your model with: Doctrine_Table finder methods Doctrine_Table::find() – by primary key Doctrine_Table::findAll() Doctrine_Table::findBy() – by specified key Others Doctrine Query Language SQL like syntax Translation to native SQL handled by Doctrine Similar to various Zend_Db statement classes
Querying: Finders and DQL
Please Sir, I Want Some More!

Más contenido relacionado

La actualidad más candente

Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)dannygriff1
 
What does OOP stand for?
What does OOP stand for?What does OOP stand for?
What does OOP stand for?Colin Riley
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
Task 03
Task 03Task 03
Task 03EdiPHP
 
E learning excel vba programming lesson 3
E learning excel vba programming  lesson 3E learning excel vba programming  lesson 3
E learning excel vba programming lesson 3Vijay Perepa
 
Everything You Never Wanted To Know About Net Generics
Everything You Never Wanted To Know About Net GenericsEverything You Never Wanted To Know About Net Generics
Everything You Never Wanted To Know About Net Genericsalethearichard
 
OrchardCMS module development
OrchardCMS module developmentOrchardCMS module development
OrchardCMS module developmentJay Harris
 

La actualidad más candente (8)

Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)
 
What does OOP stand for?
What does OOP stand for?What does OOP stand for?
What does OOP stand for?
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
Task 03
Task 03Task 03
Task 03
 
Doc abap
Doc abapDoc abap
Doc abap
 
E learning excel vba programming lesson 3
E learning excel vba programming  lesson 3E learning excel vba programming  lesson 3
E learning excel vba programming lesson 3
 
Everything You Never Wanted To Know About Net Generics
Everything You Never Wanted To Know About Net GenericsEverything You Never Wanted To Know About Net Generics
Everything You Never Wanted To Know About Net Generics
 
OrchardCMS module development
OrchardCMS module developmentOrchardCMS module development
OrchardCMS module development
 

Destacado

My first zf presentation part two
My first zf presentation part twoMy first zf presentation part two
My first zf presentation part twoisaaczfoster
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMJonathan Wage
 
Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Ralph Schindler
 
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Ryan Mauger
 
IoT Devices, Which One is Right for You to Learn
IoT Devices, Which One is Right for You to LearnIoT Devices, Which One is Right for You to Learn
IoT Devices, Which One is Right for You to LearnToni Haryanto
 
Basis Data Non Relasional: NoSQL dan MongoDB
Basis Data Non Relasional: NoSQL dan MongoDBBasis Data Non Relasional: NoSQL dan MongoDB
Basis Data Non Relasional: NoSQL dan MongoDBRiana Dwiningtyas
 

Destacado (6)

My first zf presentation part two
My first zf presentation part twoMy first zf presentation part two
My first zf presentation part two
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
 
Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2
 
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
 
IoT Devices, Which One is Right for You to Learn
IoT Devices, Which One is Right for You to LearnIoT Devices, Which One is Right for You to Learn
IoT Devices, Which One is Right for You to Learn
 
Basis Data Non Relasional: NoSQL dan MongoDB
Basis Data Non Relasional: NoSQL dan MongoDBBasis Data Non Relasional: NoSQL dan MongoDB
Basis Data Non Relasional: NoSQL dan MongoDB
 

Similar a Zend Framework And Doctrine

Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxdanhaley45372
 
Django tutorial
Django tutorialDjango tutorial
Django tutorialKsd Che
 
one|content : joomla on steroids
one|content : joomla on steroidsone|content : joomla on steroids
one|content : joomla on steroidsPaul Delbar
 
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...Bill Buchan
 
Design Patterns
Design PatternsDesign Patterns
Design Patternsimedo.de
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
George McGeachie's Favourite PowerDesigner features
George McGeachie's Favourite PowerDesigner featuresGeorge McGeachie's Favourite PowerDesigner features
George McGeachie's Favourite PowerDesigner featuresGeorge McGeachie
 
Dita for the web: Make Adaptive Content Simple for Writers and Developer
Dita for the web: Make Adaptive Content Simple for Writers and DeveloperDita for the web: Make Adaptive Content Simple for Writers and Developer
Dita for the web: Make Adaptive Content Simple for Writers and DeveloperDon Day
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
Build Your Own Instagram Filters
Build Your Own Instagram FiltersBuild Your Own Instagram Filters
Build Your Own Instagram FiltersTJ Stalcup
 
Finding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento CodeFinding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento CodeBen Marks
 
Web Performance Tips
Web Performance TipsWeb Performance Tips
Web Performance TipsRavi Raj
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 

Similar a Zend Framework And Doctrine (20)

FLossEd-BK Tequila Framework3.2.1
FLossEd-BK Tequila Framework3.2.1FLossEd-BK Tequila Framework3.2.1
FLossEd-BK Tequila Framework3.2.1
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 
Knockout in action
Knockout in actionKnockout in action
Knockout in action
 
Web 2.0
Web 2.0Web 2.0
Web 2.0
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
one|content : joomla on steroids
one|content : joomla on steroidsone|content : joomla on steroids
one|content : joomla on steroids
 
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Symfony 2
Symfony 2Symfony 2
Symfony 2
 
Entity Framework 4
Entity Framework 4Entity Framework 4
Entity Framework 4
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
George McGeachie's Favourite PowerDesigner features
George McGeachie's Favourite PowerDesigner featuresGeorge McGeachie's Favourite PowerDesigner features
George McGeachie's Favourite PowerDesigner features
 
Dependency injectionpreso
Dependency injectionpresoDependency injectionpreso
Dependency injectionpreso
 
Dita for the web: Make Adaptive Content Simple for Writers and Developer
Dita for the web: Make Adaptive Content Simple for Writers and DeveloperDita for the web: Make Adaptive Content Simple for Writers and Developer
Dita for the web: Make Adaptive Content Simple for Writers and Developer
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Build Your Own Instagram Filters
Build Your Own Instagram FiltersBuild Your Own Instagram Filters
Build Your Own Instagram Filters
 
Finding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento CodeFinding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento Code
 
Web Performance Tips
Web Performance TipsWeb Performance Tips
Web Performance Tips
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 

Zend Framework And Doctrine

  • 1. Zend Framework and Doctrine Putting the M in Zend
  • 2. A Few Notes… On the presentation: For the so inclined, the “model object” referred to is equivalent to the DDD domain object (I think). On Me: Isaac Foster Zend Framework Certified Currently working for Tabula Digita.
  • 3. Your Honor, I Intend to Prove… That Doctrine’s value added over Zend_Dbis the framework it provides for business logic. Other features make it a complete, powerful tool.
  • 4. First TLA: MVC Model – Behavior and data of the application. View– Display information. Controller– Takes inputs from the user, invokes the model and chooses the view.
  • 5. The M in MVC Model objects hold business data and logic. Model != DB: True, data that a model acts on is often persisted in a db. Db code in the model layer, not necessarily model object. Model object should focus on what makes it special. your models -->
  • 6. Separate Business and Persistence Logic DBAL (Database Abstraction Layer) One API to rule them all. ORM (Object Relational Mapper) Put the object in, get the object out. ↑Consistency, ↑Reliability, ↑Reuse, ↑Ease… It’s a Good Thing Snoop shares his thoughts on the active record pattern.
  • 7. Frameworks and Libraries Help us Achieve These (and other) Goals and one of those frameworks is…
  • 8.
  • 9. Great View and Controller framework:
  • 10.
  • 12. Zend_Session for session management… what about M?
  • 13. The M in Z-E-N-D? Zend_Db wraps db driver for DBAL. Zend_Db_Table wraps a table, gives some structure to a model, ORM-ish. Zend_DB_Table_Row wraps row, active record features.
  • 14. The M in Z-E-N-D? Provides: Protection from SQL Injection Query Construction API Transactions Profiler Cache
  • 15. So What’s the Problem? Definitely Zend_Db, not Zend_Model Not much from a business logic perspective: Little help you stay DRY with business logic. Not much in the way of model life-cycle hooks (preSave, postSave, preDelete, etc). Still thinking about db’s, tables, and table references, not models and relationships.
  • 16. Doctrine is…DBAL + ORM + Active Record + Model Framework Provides framework for business logic… Plugins hook into events, core code untouched. Reuse code and structure with behaviors. Configure validation and rules. Doctrine model IOC ≈ ZF controllers IOC Think more about models, not tables.
  • 17. Doctrine Will create your database tables. Migration tools. Performance tools and configurations. Utilities Command line interface Pagination
  • 18. Let’s Take It For a Spin
  • 19. A Problem To Solve… Need to keep track of Users Auto incremented id. Email property must be valid email address. Password must be hashed. Want to send a confirmation email to new users after they register.
  • 21. A Harder Problem… Exercise 1st Amendment right to blog Need to update blog post, track previous versions. Want to attach images to a post. Store them on Amazon S3 Update author’s numPosts field after blogging. Don’t feel like creating tables manually.
  • 24. Guideposts Doctrine_Connection ≈ Zend_Db Doctrine_Table ≈ Zend_Db_Table_Abstract Doctrine_Record ≈ Zend_Db_Table_Row_Abstract
  • 25. Doctrine Core Classes Doctrine_Manager Manages connections, knows available drivers. Handles application wide options. Doctrine_Core Manages autoloading. Methods to create tables, export database, etc.
  • 26. Connections Connect to a database: MySql, MsSql, Oracle, Postgre, DB2, Sqlite.
  • 27. Bootstrapping Connections and autoloading in bootstrap. Doctrine autoloader for models. Zend Autoloader for Doctrine library files.
  • 28. Defining Models: Goal Model creation should be like Lego building. Configure when possible, code if necessary. Let framework do the easy stuff. Leverage framework for harder stuff.
  • 29. Defining Models Each model has a Doctrine_Table. Structure and meta-info stored there. setTableDefinition and setUp create the table: hasColumn -> add properties hasOne -> add one-to-one relationships hasMany -> add one-to-many and many-to-many Model can be defined in code or YAML config.
  • 30. A More Detailed Problem… Need a Blog model with: Unique integer key. Title (non null, less than 150 chars) Text (non null). Flag for whether it is published (default false). Foreign key for relating to the author. DETAILS, REQUIREMENTS, RULES!! WHAT TO DO!!
  • 32. Doctrine_Record::hasColumn() Adds properties to your model. Blog has a title property, content property, etc. hasColumn($name, $type [,$length, $options]) name – “propertyName” or “columnName as propertyName” type - int, string, boolean, float, many more. length – max length options – options
  • 33. Property Options default – sets default value. primary – if the primary key. autoincrement – if autoincrementing id. notnull – enforce the value not be null. email – enforce the value be a valid email. Other validator indicators
  • 34. More Details… Blog also needs: An Author. Images attached to it for upload and display. WHAT TO DO!!
  • 36. Doctrine_Record ::hasOne() Defines one-to-one associations between your model and another. hasOne($associationClass [, $options]) associationClass –either “associationClass” or “associationClass as associationName” options – the association options
  • 37. Doctrine_Record::hasMany() Add one-to-many, many-to-many associations. A Blog has Comments (1-to-many). A User can be in many Groups and a Group can have many Users (many-to-many). hasMany($associationClass [, $options]) name – “associationClass” or “associationClass as associationName” options – association options
  • 38. More Problem Specs… When… The blog is created: An email should be sent to all editors informing them they need to proof read it. The blog is published: An email should be sent to the mailing list informing them of the new post. A Facebook story should be published doing the same. A Tweet should be sent with the fist 140 characters. The blog is saved (inserted or updated). All image objects associated with it must be uploaded to Amazon S3
  • 39. Note That… Stuff happens when other stuff happens. On X, do Y. Not Blog’s responsibility to email, Facebook, Tweet, or upload to S3. Probably shouldn’t be hardcoded into Blog class. COMPLEXITY!! AND YOU WANT ARCHITECTURAL PURITY!!! LAAAAMMMEE!!!
  • 40. Plugins (Listeners) As Zendfront controller pluginshook into preDispatch, postDispatch, etc, events… …so Doctrine record pluginshook into: pre/post Insert/Update/Save/Delete, others. Also plugins for connections. Hook into: pre/post connect/transactionBeing/fetch/exec, others.
  • 41. Plugins (Listeners) IOC: add logic to a model or connection without touching the core code. Log and profile all SQL queries (connection hooks). Send an email to a user when they sign up (model hooks). Register as many as you need. Similar to JS DOM events.
  • 42. Step One: Create the Plugins
  • 43. Step Two: Add the Plugins
  • 44. Doctrine_Record::addListener() Add a plugin to run when something happens. addListener($listener, $listenerName = null) listener the plugin to add. listenerName name of the plugin, useful for removing later.
  • 45. More Problem Specs… The Blog must… Keep track of when it was created and last updated. Timestamps should be set automatically, not explicitly by consumer code. Keep track of previous versions. Provide revert and get versions methods. Versioning happens automatically, not in consumer code. Be flaggable. Provide a flag method. Automatically increment the Blog’s flag count.
  • 46. Notice That… These behaviors are generic: Probably want them elsewhere, but in different combinations, with different configurations. Implementation not special to Blog. Define base classes for each and extend… …But no multiple inheritance in PHP. I’VE HAD ALL I CAN STANDS, AND I CAN’T STANDS NO MORE!
  • 47. Mix-in With Templates Avoid single inheritance issues. Don’t choose between extending Flaggable, Taggable, Locateable, Versionable, just mix-in all of them! Stay DRY. Inversion of (model definition) control. Add properties, relationships, plugins,… and methods! Encapsulate generic behavior in one place. Add as many as you want.
  • 48. Defining Models: BehaviorsStep One: Find a Template… In “path/to/Doctrine/Template” Community contributed at http://trac.doctrine-project.org/browser/extensions?rev=7461
  • 50. Defining Models: BehaviorsStep Two: Tell Your Model to “actAs” the Template
  • 51. Doctrine_Record::actAs() Adds a template to your model. actAs($template[, $options]) $template – template name or instance. $options – configuration options
  • 52. Defining Models: Summary Model creation should be like Lego building. Snap on properties and relationships. Snap in listeners that get called at hook points. Snap on behavior with templates.
  • 53. Querying Models Query your model with: Doctrine_Table finder methods Doctrine_Table::find() – by primary key Doctrine_Table::findAll() Doctrine_Table::findBy() – by specified key Others Doctrine Query Language SQL like syntax Translation to native SQL handled by Doctrine Similar to various Zend_Db statement classes
  • 55. Please Sir, I Want Some More!
  • 56. More!! You Want More! Will create tables in DB for you. Doctrine_Core::createTablesFromModels($path) Doctrine_Core::createTablesFromArray($models) Command line. Caching Memcached, APC, DB Migration tools. Performance tools. Pagination, other utilities.
  • 57. Problem Solved Life is easy now!
  • 59. Appendix: Other Resources Zend Casts (great for other stuff too) http://www.zendcasts.com/category/screencasts/databases/doctrine-databases/ Doctrine 1.2 Documentation http://www.doctrine-project.org/projects/orm/1.2/docs/manual/introduction/en Matthew WeierO'Phinney’s Blog http://weierophinney.net/matthew/archives/220-Autoloading-Doctrine-and-Doctrine-entities-from-Zend-Framework.html Google it!

Notas del editor

  1. Don’t worry too much about the presentation notes.Give brief shameless plug for TD
  2. Giving this presentation made me think about why I like Doctrine over Zend_Db, if I’m going to put something on the internet I want to be able to back it up.Made me realize that Zend_Db is called that for a reason, and that reason is that it is all about persistence logic, not business logic.Doctrine does all the persistence stuff, and has lots of powerful persistence stuff you’d want and even expect, but Zend_Db does too. Sure maybe I like Doctrine’s interface for that a little better, but that’s not the driving force behind why I use Doctrine over Zend_Db.It’s the Model IOC, model framework, model way of thinking about to approach a problem that makes it stand out in my mind.In the same way that Zend controller and view components make me think on Zend terms, Doctrine makes me think on Doctrine terms.Talk briefly about what this presentation is (at least intended to be). Trying to show what makes Doctrine special, and the problems it can help you solve that Zend can’t.Assuming you know nothing about Doctrine, but know ZF basics (VC architecture, generally aware of how things work, if not many specifics.)
  3. Quick basic intro, don’t dwell on this too much. Ask for questions, but hopefully this is relatively well understood.
  4. Also don’t want to spend too much time here, but do want to get across that model is not database, and while persistence logic certainly belongs in model layer, model object shouldn’t have to worry about it.Need to talk about distinction between model layer and model object.Code being in model layer means it’s encapsulated from controller and view.
  5. These are some key patterns in achieving the desired separation between persistence and business logic.Say there are other benefits like no SQL injection, talk about model code portability.Not too much time here.
  6. Spent almost no time here, it’s only a segue to the next section.
  7. Take notes from the slide more or less. Want to emphasize how good it is. But lead into what it’s missing.Talk about Extend Zend_Controller_Action, add action method and view scripts, page magically appears!
  8. same
  9. same
  10. Does have _post Update/Insert/Delete/Save methods in Zend_Db_Table_Row_Abstract, can over ride insert/update/delete in table class but only method hooks, can’t add listeners at will, and means you have to extend to alter (not necessarily terrible, but can be troublesome).Probably being a little harsh here, you can enforce data types and what not.Not a criticism of Zend_Db: zend db does exactly what it is trying to do.Defining model with refTables, dependentTables, etc.MW Phinney says there will be no Zend_Model because…Why I’d like a model component.
  11. Talk about plugins and behaviors.Talk about “think about models, not tables”, not quite true, but definitely more so.
  12. So I’ve talked up Doctrine a whole bunch, let’s see how it handles some basic situations.
  13. Doctrine_Connection ≈ Zend_Db“Doctrine_Connection is a wrapper for a database connection.”Doctrine_Table ≈ Zend_Db_Table_Abstract“Doctrine_Table holds the schema information specified by the given component (record).”Doctrine_Record ≈ Zend_Db_Table_Row_Abstract“Instances of (subclasses of Doctrine_Record represent) records in the database and you can get and set properties on these objects.”DBAL, ORM, Active Record
  14. Explain what you mean by “configure when possible, code if necessary”A lot of your model code is repetitive: getters, setters, validation, etc, can all be handled generically.Abstract away as much as you can into base classes (ie of a framework) and let it do most of the work, add ad hoc behavior when needed.
  15. Talk about Doctrine TablesNot necessarily unlike Zend_Db_Table, but is a table in a much more abstract sense of the word, rows and columns, as opposed to Zend_Db_Table which ends up acting like and RDBMS table.
  16. Slightly more details
  17. Rules and validation
  18. Talk about IOC ZF controllers to give context.
  19. Templates can be configured.Modify behavior, class used, column name,…Configure with actAs or template constructor.See each template’s options property for full list.
  20. Properties and relationships obviate lots of code.Over riding magic setter and listeners let you add logic where it’s needed.Behaviors let you define once and snap on anywhere. Good cause it makes you think abstractly about what behaviors are really unique to a model, as opposed to generic .