Thursday, March 5, 2009

CLI/Console program with Zend Framework

You can google this tutorial "PHP frameworks, Part 5: Integrating external tasks" for dealing with working outside the frameworks.

Even for a web application, we may need to run scripts in command line in some cases. For example, a cron job. And we want to use our models and Zend framework components. The most important thing is to setup include path to include your Zend library and your models. For example, if Zend is placed in 'library' folder, we can
set_include_path('.' . PATH_SEPARATOR . ROOT_DIR . '/library/'
. PATH_SEPARATOR . ROOT_DIR . '/application/models/'
. PATH_SEPARATOR . get_include_path());

require_once('Zend/Loader.php');
Zend_Loader::registerAutoload();

That is it. Now you can use your models and Zend components as you use them in your web application. For example,

$config = new Zend_Config_Ini(ROOT_DIR . '/config/config.ini', 'cli');
Zend_Registry::set('config', $config);
//set up default time zone
date_default_timezone_set($config->date_default_timezone);

// configure database and store to the registery
$db = Zend_Db::factory($config->database);
Zend_Db_Table_Abstract::setDefaultAdapter($db);
Zend_Registry::set('db', $db);

//do sth
$user = new User();
$user->save();

$logFile = Zend_Registry::get('config')->logFile;
$log = new Zend_Log(new Zend_Log_Writer_Stream($logFile));
$log->info('a new user is saved');

No comments: