Categories
PHP

Using Zend Models (Zend_Db_Table) with non ZF php apps

The scenario is simple: You’re building an awesome php application but for some reasons you can’t use Zend Framework. You’re a ZF fan and used to depending on Zend_Db_Table variants for your ZF models. Now, thanks to the ZF’s loosely coupled nature, you can load and use ZF components in other apps quite easily. Long ago, I wrote a blog post on how to couple ZF components with Code Igniter. Today, I am going to demonstrate the use of a simple autloader to load and use Zend_Db_Table in a vanilla php app.

Here’s the source code:

First make sure, Zend Framework is in your PHP include path. You can add the location of ZF library to php.ini or use the ini_set() function to set the appropriate value for “include_path”. This is pretty simple, so I am not going to elaborate.

Now we define a simple “load_class” function. And then register it as the autoloading handler. When the script tries to interact with a class, the class name is passed to the function. The function then includes appropriate file. Zend components follow the PEAR convention of naming. So, Zend_Foo_Bar class lives in “Zend/Foo/Bar.php”. Depending on the file name passed, we convert the name to PEAR standard and include the file. Done that, we are now free to use any class from the Zend library and it’ll be automatically loaded.

Before we can define our model, we have to instantiate a database adapter. We used Zend_Db_Adapter_Pdo_Mysql which is based on the PDO driver for MySQL. The configuration is pretty simple.

Now, we extend Zend_Db_Table_Abstract to form our “worker” class which is actually a Zend_Db_Table object. We can use all the methods and features Zend_Db_Table provides in “worker”.

The rest of the code is just self explaining. I just love how flexible and extensible Zend Framework is! 🙂

Links to ZF APIs:
Database Adapter
Zend_Db_Table