Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Zend Framework And Doctrine


Published on

From August 30, 2010 presentation at ZF NYC Meetup. I gave a presentation on why to use Doctrine, the problems it can solve, how to use it, and some basics of integrating it with the Zend Framework.

  • Be the first to comment

Zend Framework And Doctrine

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