#native_company# #native_desc#
#native_cta#

Running PHP and Zend Framework Scripts from the Command Line Page 2

By W. Jason Gilmore
on January 4, 2011

Executing Zend Framework Scripts Using the CLI

Previously I mentioned that I use the Zend Framework’s Zend_Service_Amazon component within CLI scripts. While it’s indeed possible to use Zend Framework components outside of the context of a Zend Framework application, I actually prefer to use Zend Framework-integrated CLI scripts in conjunction with an existing Zend Framework-driven website. This allows me to take advantage of the website’s existing application.ini file when running the CLI scripts, thereby keeping my application code DRY.
Zend Framework-integrated CLI scripts behave identically to a traditional Web-based Zend Framework application, requiring the application resources to be initialized with each script invocation. This is done using a custom bootstrap file, which is executed before the CLI script. Mine looks like this (named cli.php and placed in the application’s public directory):

<!--p
 
// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH',
              realpath(dirname(__FILE__) . '/../application'));
 
// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV',
              (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV')
                                         : 'development'));
 
require_once 'Zend/Application.php';
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);
 
$application-->bootstrap();

With the custom bootstrap file in place, you can then proceed using Zend Framework components and other application resources within your CLI scripts:

<!--p
  include "../public/cli.php";

  // Retrieve the public and private Amazon web service keys
  $amazonPublicKey = 
    Zend_Registry::get('config'-->amazon->product_advertising->public->key;
  $amazonPrivateKey = 
    Zend_Registry::get('config')->amazon->product_advertising->private->key;
  $amazonCountry = 
    Zend_Registry::get('config')->amazon->product_advertising->country;

  // Connect to the Amazon Web service
  $amazon = 
    new Zend_Service_Amazon($amazonPublicKey, $amazonCountry, $amazonPrivateKey);

  ...

?>

Are you using the PHP CLI for any custom command-line tasks? If so, tell us about them in the comments!

About the Author

Jason Gilmore is founder of the publishing, training, and consulting firm WJGilmore.com. He is the author of several popular books, including “Easy PHP Websites with the Zend Framework”, “Easy PayPal with PHP”, and “Beginning PHP and MySQL, Fourth Edition”. Follow him on Twitter at @wjgilmore.