#native_company# #native_desc#

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):

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

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

  include "../public/cli.php";

  // Retrieve the public and private Amazon web service keys
  $amazonPublicKey = 
  $amazonPrivateKey = 
  $amazonCountry = 

  // 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.