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

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Don’t worry too much about the presentation notes.Give brief shameless plug for TD
  • 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.)
  • Quick basic intro, don’t dwell on this too much. Ask for questions, but hopefully this is relatively well understood.
  • 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.
  • 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.
  • Spent almost no time here, it’s only a segue to the next section.
  • 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!
  • same
  • same
  • 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.
  • Talk about plugins and behaviors.Talk about “think about models, not tables”, not quite true, but definitely more so.
  • So I’ve talked up Doctrine a whole bunch, let’s see how it handles some basic situations.
  • 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
  • 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.
  • 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.
  • Slightly more details
  • Rules and validation
  • Talk about IOC ZF controllers to give context.
  • 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.
  • 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 .
  • 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 http://trac.doctrine-project.org/browser/extensions?rev=7461<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 />http://www.zendcasts.com/category/screencasts/databases/doctrine-databases/<br />Doctrine 1.2 Documentation<br />http://www.doctrine-project.org/projects/orm/1.2/docs/manual/introduction/en<br />Matthew WeierO'Phinney’s Blog<br />http://weierophinney.net/matthew/archives/220-Autoloading-Doctrine-and-Doctrine-entities-from-Zend-Framework.html<br />Google it!<br />
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.