Doctrine ORM is a PHP library that implements the ActiveRecord pattern we have all grown to love. I’ve been using it for the past 7 months and feel it is one of the reasons we were able to deliver the MessageBoards web application on-time and within budget.
This doesn’t mean using Doctrine has been all flowers and sunshine: Doctrine will kick you in the face when you’re not paying attention.
Today I’d like to revisit all of those black eyes and bloody noses in the hope of helping fellow developers avoid the same missteps I made. Doctrine is complex and quirky, and has some unanticipated architectural “features” that are not well documented.
Use Record::toArray() and Record::fromArray() to store/retrieve Doctrine objects from the session.
- Save space in the session store by adding only the column attributes of Record objects to the session.
- The session will quickly fill up otherwise, as Doctrine adds considerable bulk to model objects.
Improve performance by extending Doctrine_Table and implement custom DQL queries for complex and frequently used queries.
- If the controller or view will need a record’s related record, use a DQL query to join with the related table.
Optimize performance by getting to know and love Doctrine_Connection_Profiler.
- Add the connection listener at the beginning of execution and print SQL queries at the end of execution in order to identify areas of effective performance optimization.
- Example code that adds the listener and renders query events as HTML:
// Set the connection listener $profiler = new Doctrine_Connection_Profiler(); Doctrine_Manager::connection()->setListener($profiler); // Code goes here... // Render database connection events as HTML: $query_count = 0; $time = 0; echo "<table width='100%' border='1'>"; foreach ( $profiler as $event ) { if ($event->getName() != 'execute') { continue; } $query_count++; echo "<tr>"; $time += $event->getElapsedSecs() ; echo "<td>" . $event->getName() . "</td><td>" . sprintf ( "%f" , $event->getElapsedSecs() ) . "</td>"; echo "<td>" . $event->getQuery() . "</td>" ; $params = $event->getParams() ; if ( ! empty ( $params ) ) { echo "<td>"; echo join(', ', $params); echo "</td>"; } echo "</tr>"; } echo "</table>"; echo "Total time: " . $time . ", query count: $query_count <br>\n ";
Effectively mitigate performance issues with memcache.
- The query and result cache can drastically offset Doctrine’s performance overhead.
- If you already have memcached running, this is one of the most cost-effective performance tweaks you can do.
- Note: I received mysterious fatal errors when using INDEXBY in DQL queries. After removing the INDEXBY, the errors stopped.
Play nice with fellow coders or testers by automating database migrations.
- Add a git merge hook that runs the Doctrine migration.
- Alternatively, check if a migration is needed on every page view while in development mode.
Play nice with other web applications by prefixing database tables.
- Set the table name prefix by calling $this->setTableName(’zzz_model_name’), where ‘zzz’ is the tool’s prefix.
Create a “resource-oriented” URL structure that closely follows the application’s models.
- This is borrowed from the RESTful architecture, and not necessarily Doctrine-specific.
- For example an HTTP GET on http://site.com/messageboard/m34/f11/ would display forum ID 11 in messageboard 34 in tool “messagebord”.
Use a workaround when using LEFT JOINs on models with actAs(’SoftDelete’) behavior.
- SoftDelete will automatically add the WHERE condition “deleted = 0″ to all queries.
- This prevents queries with LEFT JOIN from returning a row where “deleted IS NULL”.
- Either use INNER JOIN instead, or add the following to DQL queries: $query->andWhere(’deleted = 0 or deleted IS NULL’);
Timestampable cannot be disabled temporarily, causing challenges when importing data with dates.
- Doctrine provides no way to easily disable or override the timestamp behavior in order to import a pre-existing date.
- Until this behavior is resolved, try using this patch to set the ‘disabled’ option of Timestampable.
Use “cascade => array(’delete”)” to propagate soft deletes through model relations.
- The faster onDelete => ‘CASCADE’ performs the delete in MySQL, which does not set the deleted flag.
Put authorization code in one place, when possible.
Implement checkbox plus text input as two columns in a model.
- For example:
Require password:
- This approach simplifies validation of optional attributes.
Use $model->setAttribute(Doctrine::ATTR_COLL_KEY, ‘id’) to key collections off of the primary key.
- If this attribute is not set, Collections will be indexed starting from 0 and counting upwards.
- This can simplify controller logic.
Use Doctrine_Pager only for the most basic views.
Use actAs(’NestedSet’) to model hierarchies that are read more frequently than written.
Use unix timestamps in Timestampable columns to ease formatting.
- Using a datetime works fine if the view never needs to change how a datetime is displayed.
- A unix timestamp allows for flexibly changing how dates are rendered, e.g.: “Jan 1st 2008″ or “Yesterday”.
- Example actAs() code:
$this->actAs('Timestampable', array( 'created' => array('name' => 'created_at', 'type' => 'integer', 'format' => 'U', 'disabled' => false, 'options' => array()), 'updated' => array('name' => 'updated_at', 'type' => 'integer', 'format' => 'U', 'disabled' => false, 'options' => array())));
For multi-step forms, add a ’state’ column to aid in validating each step.
- In the model’s validate() function, use the state column to switch between validation logic.
- For instance, in state 1, validate columns a and b. In state 2, validate columns a, b, c, and d. In state 3, validate the complete object.
I hope this list saves some heartache on what is really a very elegant ActiveRecord implementation in PHP!
Great tips. Doctrine is indeed powerful and quirky. Thanks!
Thanks for the writeup. We are using doctrine for developing a new application, and have come across much of the same issues.
One issue that came up specific to our test host, Mosso, is that when we tried doing things using doctrine objects for fetching information, we would get “no suitable nodes are available” type errors from the server. When we changed these over to DQL, no problem.
Thank’s for the tips ! But I actually wonder if it’s possible to include behaviors in doctrine migrations ?
“Play nice with fellow coders or testers by automating database migrations.” – It would be very helpful if you could elaborate on this in another post.
I am interested in the ability to modify a YAML schema file–add fields, remove tables, modify behaviors–and then run a script to compare it to the database or old models (using the diff tool) and auto-update the model classes and database. I’m getting a lot of errors the way I’m trying to do it, and I was convinced that Doctrine was just buggy until I read your post. Please let us know more!