Zend Framework: (1) Integrating Firebug and FirePHP with ZF
This is my first post out of a series of articles on Zend Framework. Zend Framework is the official Framework by Zend Corporation, maker of the well-known PHP language. It supports the creation of web applications by providing basic functionality for daily use.
Especially as a starter in Zend Framework, you will need some simple tools to debug your first steps with that new, huge system. Since version 1.6, Zend Framework integrates FirePHP in it’s library. FirePHP integrates your PHP application with your Firebug (which is in fact an Firefox addon). The official web site describes FirePHP at it’s best:
FirePHP enables you to log to your Firebug Console using a simple PHP method call.
All data is sent via response headers and will not interfere with the content on your page.
FirePHP is ideally suited for AJAX development where clean JSON and XML responses are required.
From my side, the most important function of FirePHP in Zend Framework is the logging of database queries. To enable logging, just add the following lines to your application.ini:
resources.db.setDefaultTableAdapter = 1
resources.db.params.profiler.enabled = true
resources.db.params.profiler.class = Zend_Db_Profiler_Firebug
FirePHP will now add any SQL queries via Zend_DB to the Firebug Console. It also includes the query time and the result table. This allows debugging at a glance.
But be aware of the section you add it to: Always keep in mind that adding it to the [production] section might be a huge security risk if you forget to remove it once you set your page live. On the other hand, you don’t have to remove any of the debug calls in the code and just change profiler.enabled to false for an enviroment.
To write any custom lines to the Firebug debug console, just add the following to your controller:
$writer = new Zend_Log_Writer_Firebug();
$logger = new Zend_Log($writer);
This will create a new logger-object. with $logger->log(‘your message’, Zend_Log::INFO), you can directly write to the console. There are plenty ways to minimize double coded lines. My approach is to add the preDispatch()-function to the controller and assign the logger-object to an private variable of the controller class:
class MyController extends Zend_Controller_Action
{
private $_log_writer;
private $_log_logger;
…
public function preDispatch()
{
$writer = new Zend_Log_Writer_Firebug();
$logger = new Zend_Log($writer);$this->_log_writer = $writer;
$this->_log_logger = $logger;parent::preDispatch();
}
You may also be able to create both writer and logger object directly in the bootstrap and assign it to Zend_Registry. I personally prefer this method, because adding both objects to the bootstrap means that they will get loaded at any HTTP request.
To keep the console messages appropriate, you can use any of the priority constants that are provided by Zend_Log. A whole list (seven priorities) is available in the documentation.