Categories

Subscribe

Please Subscribe Here to Get UpdatesLeave This Blank:Leave This Blank Too:Do Not Change This:

Your email:

ORM – Object Relational Mapping in PHP

ORM- Object Relational Mapping is a tool which allows database row to refer as object in PHP programming. What Wikipedia says about ORM is:

Object-relational mapping (ORM, O/RM, and O/R mapping) in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a “virtual object database” that can be used from within the programming language.

(Object-Relational Mapping) is a tool that allows you query database table and manipulate data from a database using an object paradigm (Object Oriented).

ORM is library which helps you in query the data using functions so that PHP developer do not have to write database query manually. It uses model objects to get the database table’s data.

Let understand this with simple example code. You have a book class and you want to fetch the books whose author is ‘Peter’. To get list of books, you may write similar kind of code as follow:

PHP

1

2

3

4

5

6

7

8

$book_list=newList();

$sql="SELECT * FROM books WHERE author = 'Peter'";

$result=mysql_query($sql);// I over simplify ...

while($row=mysql_fetch_assoc($result)){

$book=newBook();

$book.setAuthor($row.get('author');

$book_list.add($book);

}

Above code using ORM can be written as simple as follow:

PHP

1

$book_list=Book.query(author="Peter");

All the mechanical part is taken care by the ORM. You write almost no query retrieving the data from table/s.

Advantages

ORM saves time because:

It uses DRY concept. You write your data model in only one place, it’s easier to update, maintain and reuse the code.

A lot of stuff for database manipulation is done automatically, maintaining relation and fetching data is also some times automatically.

It forces you to write code in MVC (Model-View-Controller) structure, so in the end your application code will be cleaner.

You don’t have to write formed SQL statements, complex relational query are handled by ORM

Sanitizing, using prepared statements or transactions are as easy as calling a method.

ORM is flexible to use:

It fits in your natural way of coding.

It abstracts the DB system, so you can change it whenever you want.

The model is weakly bound to the rest of the app, so you can change it or use it anywhere else.

It let you use OOP goodness like data inheritance without head ache.

Disadvantages

You have to learn it, and they are not lightweight tools;

You have to set it up. Same problem.

Performances are ok for usual queries, but a SQL master will always do better with his little hands for the big dirty works.

It abstracts the DB. While it’s ok if you know what’s happening behind the scene, it’s a trap for the novice that can write very greedy statements, like a heavy hit in a “for” loop.