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!
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
Zend Framework and Doctrine Putting the M in Zend<br />
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 />
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 />
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 />
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 />
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 />
Frameworks and Libraries Help us Achieve These (and other) Goals<br />and one of those frameworks is…<br />
Zend_Session for session management</li></ul>… what about M?<br />
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 />
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 />
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 />
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 />
Doctrine<br />Will create your database tables.<br />Migration tools.<br />Performance tools and configurations.<br />Utilities<br />Command line interface<br />Pagination<br />
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 />
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 />
Connections<br />Connect to a database:<br />MySql, MsSql, Oracle, Postgre, DB2, Sqlite.<br />
Bootstrapping<br />Connections and autoloading in bootstrap.<br />Doctrine autoloader for models.<br />Zend Autoloader for Doctrine library files.<br />
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 />
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 />
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 />
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 />
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 />
More Details…<br />Blog also needs:<br />An Author.<br />Images attached to it for upload and display.<br />WHAT TO DO!!<br />
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 />
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 />
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 />
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 />
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 />
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 />
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 />
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 />
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 />
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 />
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 />
Defining Models: Behaviors…or Make Your Own<br />
Defining Models: BehaviorsStep Two: Tell Your Model to “actAs” the Template<br />
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 />
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 />
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 />