Posts Tagged ‘Usage of DAO pattern in PHP’

Usage of Data Access Object (DAO) pattern in PHP

May 31st, 2010

Data Access Object pattern is a heavily used design pattern used in J2EE, but good thing is that it could be used in a very efficient manner in PHP.

What is DAO pattern?

The very first thing we need to understand is what is DAO pattern. In our last blog on DTO, it is emphasized that Data Object is an exact replica of a database table with getter and setter methods for the fields.

Let’s assume that a database connection is created in the controller or in the managed bean of JSF and dataobject is populated with the results. Now i need to execute the same query in another controller or managed bean than i need to again write the same query. Thus in this way our database layer is tightly coupled to the web part.

Thus to abstract the database layer, if a new layer is introduced in between web and database which provides an interface to access the database, it would decouple the database from the web layer. Also, the same query hasn’t need to be rewritten. This is what is called Data Access Object Layer.

Usage of DAO pattern

Option 1
- Create a class called EmployerDAO.php

- Let’s say i want to display the list of employers, than my function would go like in the EmployerDAO.php

public function getEmployerDetails($id)
$employerQuery = “select * from tbl_employer where employerid=’$id’”;
$tempEmployerVO = new EmployerVO();

$employerResult = mysql_query($employerQuery);
$row = mysql_fetch_array($employerResult) ;

$tempEmployerVO-> setId() = $row-> id;

$tempEmployerVO-> setFirstname() = $row->firstname;

$tempEmployerVO-> setLastname() = $row->lastname;

return $tempEmployerVO;

Thus in the controller, you would instantiate the DAO class and call this method to retrieve the dataobject of employer.

In this way wherever you want to have the enployer details, just instantiate the DAO and call the result.

The key point to note here is that if the same table is used in another php project, you can use the same DAO layer. Thus it improves the efficiency and maintenance of the code to a large extent.

Option 2

Another way you can use the same DAO layer is as the interface and different classes can implement the interface as per the requirement. This is one more level of abstraction.

It would be helpful in cases where you have different logic to be implemented before populating the dataobject.

Give it a try !!

Ushainformatique Development Team