Leaking Abstraction

Loosely coupled thoughts on web development

Using Zend_Db standalone

leave a comment »

If there is one class I had to pick out of the ZF library as the crown jewel, it would without a doubt be Zend_Db.
I rarely touch a PHP application or script that interacts with any database without utilizing this class.

Let’s go over the quick list of why it’s my fave:

  • It automatically wraps PDO extensions and normalizes them as best as possible across different types of databases (in simple terms: change from a MySQL database to an MS SQL or PostgreSQL database with minimal code change)
  • It sanitizes data input for you automatically (as long as you use it correctly)
  • You can quickly grab results in array or object form without performing any post query operations.
  • Provides methods for programatically creating queries

On top of that, it’s easily decoupled from the rest of the library. Let’s start out by ripping out Zend/Db.php and the Zend/Db folder and dropping it in our app.

Initializing the database connection

Now, in our settings / boilerplate file let’s initialize the database adapter. The database adapter uses a lazy connection (meaning it doesn’t actually connect to the database until you perform a query with it) by default. This makes the application settings a perfect place to setup our database object.

[ccew_php tab_size="4"]
$db = Zend_Db::factory('Pdo_Mysql', array(
	'host'             => 'localhost',
	'username'         => 'database_username',
	'password'         => 'database_password',
	'dbname'           => 'database'
));
[/ccew_php]

That’s easy enough. If the application is simple and you plan on referencing the $db variable every time you want to make a query, you can stop right there. If you plan on using the database connection within a function or class scope, you don’t have to re-initialize it every time (or use icky global variables). Zend_Db_Table comes with a static function for setting the default database adapter.

[ccew_php]
require_once('Zend/Db/Table.php');
Zend_Db_Table::setDefaultAdapter($db);
[/ccew_php]

And now within our classes or functions, we can easily call it at any time:

[ccew_php]
class MyClass {
	private $db;
	function __construct() {
		$db = Zend_Db_Table::getDefaultAdapter();
	}
}
[/ccew_php]

Presto. Persistent database object any time we need it in our application / script.

Advertisement

Written by Andy Baird

January 5, 2010 at 4:01 pm

Posted in Tutorials

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.