Using Data Objects(MySQL, PostgreSQL, Oracle, DB2 etc.) In PHP
I decided to switch from using arrays and use data objects for my web apps instead. One of the reason I did this is because fetching data from the database and dumping it into a object gives you much more flexibility than using regular arrays.
I remembered using data objects on a project I was working on a few months ago. The idea was a little to confusing for me at the time. Now I see that there’s more of an advantage to it than arrays could ever offer. If you run large object orientated web apps you might want to look into it…
How you do it—same as fetching a row into an array, just a different function:
<?php
// Here is an example in PostgreSQL(Can also be used in MySQL, Oracle, DB2 or what have you)
$resource = pg_query("SELECT id, name, active FROM users WHERE id = {$id} LIMIT 1");
// pg_fetch_object(sql_resource, [int row, str Class Name]);
$user = pg_fetch_object($resource, NULL, "MyClass");
// Echo some stuff
echo "Id Number: {$user->id}, User Name: {$this->username}";
?>
Pretty simple. What I like best is that it just creates an object on the fly using the stdClass(Default Standard PHP Class) and adds the database values to it. If you want to add more functionality to it you can create your own classes(it’s very straight forward).
By using this we accomplish two things:
- We have more control over our data when it’s pulled from the database.
- We’ve become more Object Orientated, therefor adding more flexibility. We also have the option to use any of PHP’s OO features such as class inheritance, the ability to use control patterns etc.
You can learn more about Postgres and PHP data objects pg_fetch_object() HERE! or MySQL’s mysql_fetch_object() HERE!
I know most developers have heard about this before, but hell—I thought it would be something cool to bring up and share with everyone.