Posts Tagged ‘PHP Design Patterns’

Usage of Data Transfer Object (DTO) Pattern in PHP

April 27th, 2010

Data Transfer Object is a heavily used design pattern used in the development of web applications requiring database interaction in J2EE. It makes the life of a developer highly easy in managing the data that is being transferred and provides a secured way of transferring the data between layers.

When i switch from J2EE to PHP and with the release of PHP5, it suddenly comes to my mind to use this concept along with Data Access Object pattern (which i will explain in my next post) from J2EE in PHP  and it worked wonderfully for me to meet any level of complex applications.

What is a Data object?

First of all, we need to understand as what is a data object. A data object is a class representing a table in the database with the field names exactly same as database column names. It contains the getter and setter methods for these fields.

Let’s say i have a table called tbl_employee having columns as

- id (int 10)

- name ( varchar(50))

Now, the dataobject would typically look like

public class Employee()

{

var $id;

var $name;

public function getId()

{

return $this->id;

}

public function setId($tempId)

{

$this->id=$tempId;

return $this->id;

}

public function getName()
{
return $this->name;
}
public function setName($tempName)
{
$this->name=$tempName;
return $this->name;
}

Now the next point is about using it and see how helpful it would turn out to be. The following function interacts with the database thus assuming database connection is available.

public function getEmployeeList()

{

$employeeList = array();

$query = “select * from tbl_employee order by name”;

$result = mysql_query($query);

while ($row=mysql_fetch_array($result))

{

$tempEmployeeDO = new EmployeeDO();

$tempEmployeeDO->setId($row['id']);

$tempEmployeeDO->setName($row['name']);

$employeeList[count($employeeList)] = $tempEmployeeDO;

}

return $employeeList;

}

Thus the above function returns the list of employees containing data objects. On the front end you need to iterate through the list where each element is a DO and than use getter method to retrieve the values.

Start using it and you will realize that it makes your life pretty easy during development.

Enjoy!!

Ushainformatique Development Team