Using Zend_Db standalone
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.
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.
And now within our classes or functions, we can easily call it at any time:
Presto. Persistent database object any time we need it in our application / script.




