Magento shell scripts

I have often seen custom shell scripts on Magento instances, be it a script testing out some code snippet or an attribute installation script which hadn’t made it’s way to a separate module. This will create a mess in the files structure as there are quite a lot files already residing in the root folder. There is, however, the dedicated place where these scripts should be placed and this place is the ‘shell’ folder in the root of every Magento installation

There are some scripts in there already, namely indexer.php (we have a blog post on its usage) and log.php, the latter allows to view logs statistic and clean them from command line. Our interest here would be abstract.php file containing Mage_Shell_Abstract class, which is extended by all actual shell scripts.

 

The class has some useful helper methods called in the class constructor which I’d like to describe.
First of all the class routine parses .htaccess variables in _applyPhpVariables() method, making sure any custom PHP settings are applied to the shell script as well. Another important method is _parseArgs() which allows data to be passed from command line to the script and stored in an internal array of variables to be accessed later.
Next method called _validate() doesn’t allows the script to be ran from browser. This way it ensures that no user can run your script’s logic by pointing browser to http://magentohost/shell/script.php
Lastly the _showHelp() method is called which prints script’s usage notices. I suggest to override usageHelp() method which it calls in turn and supply notes which are relevant for your script so that consumers know what options it can take and process.

 

Note that if your script does something not related to Magento and doesn’t need the application to be bootstrapped you can set $_includeMage to false in your script __construct() method and then call parent::__construct() in its body

 

One more hint from my experience: if you want to pass a value for a param, you have to do it by adding “–” before param name. For example script.php –order 00000001. This way it will be parsed correctly and you can get it’s value in code using $this->getArg(‘order’)

 

Now you just have to create your script.php, extend your class from Mage_Shell_Abstract, instantiate your class and call the run() method. You can find more examples in the scripts I’ve mentioned above and please don’t hesitate to ask questions if you have them.

 

I hope this mini-guide was useful for you and happy scripting!