Leaking Abstraction

Loosely coupled thoughts on web development

Running scripts in Zend Framework

leave a comment »

It’s always been a bit confusing to me where and how to execute scripts within my Zend Framework applications. Often times I would just initialize the autoloader and the classes myself in the script file itself.  Since the existence of Zend_Application, this has become a whole lot easier.

First, I create a folder called “scripts” in my application directory. This is an ideal location for scripts because it’s outside of the Apache HTTP root which means we don’t need to worry about remote execution. We can also easily point CRON jobs to this location instead of running some fangled CRON job to cURL a particular URL (Yes, I’m guilty of this, sadly).

Now, at the top of any script we write, add the following:

File: /application/scripts/anyscriptyouwrite.php
[ccew_php]
define(‘APPLICATION_ENV’,'script’);
require_once(‘../../httpdocs/index.php’);
[/ccew_php]

This sets our application environment to the “script” environment. Now, we will customize our Bootstrapper when running scripts by editing the index.php in the web root:

File: /public/index.php
[ccew_php]
if (APPLICATION_ENV == ‘script’) {
$application->bootstrap(‘Db’);
$application->bootstrap(‘Registry’);
/* ..etc.. */
} else {
$application->bootstrap()
->run();
}
[/ccew_php]

Notice, we don’t ever call the run() method, so the front controller never gets instantiated. This allows us to explicitly declare each resource we want to setup an environment more ideal for scripting.
Another cool side effect of using the APPLICATION_ENV is we can specify script-specific settings in our application.ini:

File: /application/configs/application.ini
[ccew_php]
[script : production ]
resources.db.adapter = PDO_MYSQL
resources.db.params.host = “hostname”
resources.db.params.username = “username”
resources.db.params.password = “password”
resources.db.params.dbname = “dbname”
[/ccew_php]

Advertisement

Written by Andy Baird

January 30, 2010 at 6:10 pm

Posted in Tutorials

Tagged with , ,

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.