ORM for PHP – Doctrine
I have been always dreaming about some magical component for PHP developers that would free us from the pain of handling databses. And I have mostly seen useless wrappers for native database functions of PHP. Those always tried to claim that the will make it all better. No luck. Until recently (well, a bit more than recently) I looked into a thing called ORM (Object-relational mapping). Specifically - an ORM for PHP called Doctrine.
Now, having some experience in trying to do database handling manually (e.g. having to use mysql_connect etc all the time) and letting Doctrine to do this for you I have one phrase to tell you: if you are not using ORM already you are losing a lot of precious time.
So, just as a small example of ORM godlyness. Really small and really simple. We need to create a page which holds orders from clients. Each order consists of items (duh!). This means two database entities - Orders and Items
First, let us see what we would need to do if we did not use Doctrine (or some another ORM):
- Create an SQL script for table creation (the main problem here is that SQL scripts are unreadable at all):
- CREATE TABLE 'order' (id INT NOT NULL AUTO_INCREMENT, client_name VARCHAR(255), client_address VARCHAR(255));
- CREATE TABLE 'item' (id INT NOT NULL AUTO_INCREMENT, title VARCHAR(255), cost FLOAT, order_id INT NOT NULL);
- Create classes Order and Item. This is always very annoying for one reason - you have to rewrite CRUD functions over and over and over and over again. I hate it. I am not going to write the CRUD support for those classes right now, but if you did it once - you do not want to do it again.
Well, that was pretty simple, but 1) time-consuming; 2) cofusing (you cannot see the overall scheme of things; 3) it is Boring.
Let's take a look how you can do this whole thing with Doctrine in no time. The basic idea is to create a YAML (*.yml) file, which describes your database scheme. Here is how our case would look like:
Order:
columns:
client_name: string(255)
client_address: string(255)
Item:
columns:
title: string(255)
cost: float
order_id: integer
relations:
Order:
local: order_id
foreign: id
foreignAlias: items
Voila. This is it. After that the only thing you have to do is type "php doctrine build-all-reload" in your favourite console and let Doctrine create the tables in the database and the classes for you. Right after that you can start using those to implement your business logic without caring about the CRUD functions!
In my script I could go like this right away:
// Create an order and set its vars
$order = new Order();
$order->client_name = "Vasili Pupkin";
$order->client_address = "Bobrujsk";
// Add a new item
$order[0]->title = "Saaremaa Vodka 80";
$order[0]->cost = 15;
// Add another item (which plays very well with the first item)
$order[1]->title = "Good pickles";
$order[1]->cost = 2;
// Save the order to the database
$order->save();
And that is the end of that story. Create a YAML file and start implementing the business-logic instead of spending a couple of hours (or more) writing boring monkey-oriented code.
December 17th, 2009 - 14:04
В загородном доме с установленным пленочным инфракрасным Отоплением, общей площадью 150 м 2 расход электроэнергии составляет всего ~ 3,5 кв ч.
December 20th, 2009 - 01:37
Симпoтoмы свиного гриппа будто тakиe но, на правах равным образом около oбычнoгo.
December 27th, 2009 - 06:10
Но почти все специалисты предупреждают от эйфории в связи с увеличением притока валютных средств в банки.
December 28th, 2009 - 22:11
Киев обувь в киеве, киев-магазины обуви, магазины спортивной, молодежной, классической обуви киева.