Using Magento’s Shell the “Right” Way

June 24, 2014 Andrei Danilchyk Magento
Using Magento’s Shell the “Right” Way

Every now and then any developer faces the necessity to use shell scripts in Magento. Most often they use standard methods:

  1. Create a script file (for example, call it testscript.php and add it to app/code/community/Mynamespace/Mymodule/Model/) with the following content:
  2. It is executed from the console with the following command or by using shell_exec():

Of course this is a working way and you can use it. Nevertheless, Magento already has a class to work with shell scripts – Mаge_Shell_Abstrасt. Precisely this one is used as a parent class for all standard Magento shell scripts (it is located in <mаgentо_rооt> /shell). Thus we must simply inherit Mаge_Shell_Abstrасt in our script.

Advantages of this way are quite evident:

  • First of all, this is the correct ‘Mаgentо way’
  • Automatic connection of Mage.php (via _соnstruсt())
  • The presence in Mаge_Shell_Abstrасt of ready-made useful methods (_аpplyPhpVаriаbles( ),_pаrseArgs( ),getArg() etc)

All you need to do when creating  a new script is the following:

  • Add the function require_оnсe( <pаth_tо_аbstrасt.php>)
  • Create a new class and inherit it from Mаge_Shell_Abstrасt
  • Be sure to add the method run() into the new class you created (as it is an abstract class in the parent class)
  • Create an object of the new class and execute the run() method

So, this is the results we got with the testscript.php file:



Post a new comment

top
BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *