This week I am a newbie to PHP Doctrine. So I thought I’d share some of the experiences I’ve had with it, not so much in a coding sense but in a “this is the cool stuff you can do with it” sense.
Doctrine is an ‘object relational mapper’ or ORM for short, letting you code your app in terms of the objects you require, without worrying too much about the underlying database table structure. With SQL queries, a simple 2-dimensional table of rows and columns is returned. Using an ORM, a multi-dimensional object or array can be returned with all the relationships between objects prepared for you.
In general I’m a bit of framework-sceptic, but I think this one really deserves a look as there’s some really powerful tools included.
Also the website is nicely designed and has pretty good documentation on it, which makes all the difference.
So here’s a list of 10 things I’ve learned about it this week, in no particular order:
- You can define your data structures using a simple YAML file, which while it sounds like some kind of novel pet food, is in fact dead easy to get to grips with and is very quick to type out.
- Doctrine will create PHP model objects all ready to go from the YAML file and install the necessary database tables for you.
- If you find yourself needing to change the data structure, you can do so in the YAML file and Doctrine will update the PHP scripts and the database tables aswell, while retaining the data – I think this is a great feature.
- Doctrine can guess from the YAML file what the relationships are between objects/tables, and so far seems to do a great job of it.
- If you don’t want to hand craft your YAML, you can also do various things like build the models from an existing database structure or vice versa
- You can fetch data from one object and it fetches all the related data too, eg if I fetch a blog post and it fetches all the related comments at the same time.
- You can use “Doctrine Query Language” or DQL, which is has a similar feel to SQL, but selects objects together with their relationships instead of a flat table of results. Gone are the days of laboriously typing out JOIN statements: because you’ve described the data relationships in your YAML file, Doctrine automatically joins things together for you. Nifty.
- You can hook into the models that are automatically generated allowing you to, for example, modify queries on the fly before data is requested, or modify data as it’s returned. This lets you reuse business logic efficiently that is always used on particular fields.
- There are built-in behaviours such as ‘timestampable’ or ‘sluggable’ which automatically generate timestamp fields or URL slugs (eg ‘this-is-a-nice-blog’) for particular tables
- It also has the usual suspects such as data validation – but I haven’t got to that yet…
Right, that’s it for now – if I find out anything else interesting I’ll post it here!