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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php function load_class($name) { $name = str_replace("_","/",$name); require_once $name.".php"; } spl_autoload_register("load_class"); $db = new Zend_Db_Adapter_Pdo_Mysql(array( 'host' => '127.0.0.1', 'username' => 'root', 'password' => 'xxxxxx', 'dbname' => 'worker_db' )); Zend_Db_Table_Abstract::setDefaultAdapter($db); class workers extends Zend_Db_Table_Abstract { public function getAll() { return $this->fetchAll(); } } $workers = new workers(); foreach($workers->getAll() as $worker) { echo $worker['name']."\n"; } |
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