Using Zend Framework Models and Libraries from Command Line (or Cron Job)

If you are developing web applications using the Zend Framework for PHP and you need a few cronjobs, you might be wondering if you could (re)use the existing models and libraries. Recently while working on a project, I was wondering the same thing. I have seen people asking the same thing about CodeIgniter framework before but my initial search for a suitable way to use ZF models and libs with cron was unsuccessful. It’s not like that I didn’t find any solutions, the fact is I found quite a few. Unfortunately none of them worked for me. While browsing through the search results, a post on StackOverflow caught my eyes. Someone suggested that we should take the original index.php and Bootstrap.php and hack the codes to get the core ZF running minus the views. That made sense. While running on the command line, we don’t care about the HTTP response and other stuff related with server-client communication. After half an hour of trial and error, I finally found that you can actually take the existing index.php and delete a few words off it to convert it from a web app to a command line app.

Sounds interesting? Locate these lines in the index.php file in the ZF public directory:

Here we first construct the application object, bootstrap it and then run the application. Bootstrapping automatically loads the required classes and executes them. But running the application tries to find a HTTP reuquest and process it. Since we don’t have a HTTP Request, we actually don’t need the last step. You got the hint?

Yes, after constructing the Application object, just bootstrap it, don’t run. So, take the index.php, make a duplicate copy out of it and then change the last few lines like this:

What I do, I create a another folder named “cron” parallel to the public directory, save the bootstrap file as “core.php”. Then in every cron script, I just require_once the core. php, simple, eh?


Leave a Reply

Your email address will not be published. Required fields are marked *