Usare il framework di Joomla da riga di comando

Joomla non è solo il CMS che siamo abituati ad usare per la realizzazione e gestione di un sito.

Joomla è anche il framework su cui si basa il CMS, non a caso esistono due Google Group distinti: CMS Development e Framework Development.

Possiamo usufruire delle classi e delle funzionalità che abbiamo a disposizione durante lo sviluppo di estensioni per Joomla anche per programmi standalone, magari eseguiti in cron job oppure direttamente da riga di comando.

Per fare questo, è necessario dapprima inizializzare il framework, usando il codice sotto indicato - con l'accortezza di inserire il codice della nostra applicazione all'interno della funzione execute().

Facendo alcune prove ho notato come alcuni dati del file configuration.php non vengono caricati correttamente, per la precisione quelli relativi al database - così è necessario indicarli nuovamente nel file. Se qualcuno ha una soluzione per questo problemino, è ben accetta :-)

Copiamo questo codice ed inseriamolo in un file nella root dell'installazione di Joomla: tutta la potenza offerta dal framework sarà a nostra disposizione anche eseguendo il programma da riga di comando, con l'istruzione "php nomefile.php"

 
#!/usr/bin/php
< ?php
/**
 * @version $Id$
 * @package Joomla.Example
 * @subpackage CLI
 * @copyright Copyright (C) 2008 - 2009 Louis Landry. All rights reserved.
 * @license GNU General Public License, <http://www.gnu.org/copyleft/gpl.html>;
 */
 
// We are a valid Joomla entry point.
define('_JEXEC', 1);
 
// Setup the path related constants.
define('DS', DIRECTORY_SEPARATOR);
define('JPATH_BASE', dirname( __FILE__ ));
define('JPATH_ROOT', JPATH_BASE);
define('JPATH_CONFIGURATION', JPATH_BASE);
define('JPATH_LIBRARIES', JPATH_BASE.DS.'libraries');
define('JPATH_METHODS', JPATH_ROOT.DS.'methods');
 
// Load the library importer.
require_once (JPATH_LIBRARIES.'/joomla/import.php');
require_once (JPATH_CONFIGURATION.'/configuration.php');
 
// Import library dependencies.
jimport('joomla.application.application');
jimport('joomla.utilities.utility');
jimport('joomla.language.language');
jimport('joomla.utilities.string');
jimport('joomla.factory');
 
/**
 * Simple command line interface application class for quick bootstrapping
 * things to test.
 *
 * @package Joomla.Example
 * @subpackage CLI
 * @version 1.0
 */
class JApplicationCLI extends JApplication
{
    /**
     * The name of the application
     *
     * @var array
     */
    public $_name = 'JApplicationCLI';
 
    /**
     * The client identifier.
     *
     * @var integer
     * @since 1.0
     */
    public $_clientId = 1000;
 
    /**
     * The current working directory of the application.
     *
     * @var string
     * @since 1.0
     */
    private $cwd = null;
 
    /**
     * The application argument values.
     *
     * @var array
     * @since 1.0
     */
    private $argv = array ();
 
    /**
     * The application argument options.
     *
     * The options are populated automatically by the private _initializeOptions
     * function
     * which sets each command line argument as a member of the options object.
     *
     * @var object
     * @since 1.0
     */
    private $options = null;
 
    private $shortargs = 'i:o:hflp';
 
    // Need to wait for PHP 5.3
    private $longargs = array ('help');
 
    public function __construct()
    {
        // Initialize the execution arguments.
        $this->_initializeOptions();
 
        // If the help screen has been requested, print it and exit.
        if ( isset ($this->options->h))
        {
            $this->help();
            exit (0);
 
        }
 
        // Get the current directory.
        $this->cwd = getcwd();
 
    }
 
    public function execute()
    {
	    /*
	     * Variabili per l'accesso al database
	     */
		$conf =& JFactory::getConfig();
		$conf->setValue('config.user', 		'dbuser');
		$conf->setValue('config.password', 	'dbpass');
		$conf->setValue('config.db', 		'dbname');
		$conf->setValue('config.host', 		'mysql.dbhost.com');
 
		/*
         * Inizio codice da eseguire
         */
		$db =& JFactory::getDBO();
    }
 
    /**
     * Method to print a line of text to stdout.
     *
     * @param string The line of text to print to stdout.
     * @return void
     * @since 1.0
     */
    function out($text = '')
    {
        echo "\n".$text;
    }
 
    /**
     * Method to build and print the help screen text to stdout.
     *
     * @return void
     * @since 1.0
     */
    protected function help()
    {
        // Initialize variables.
        $help = array ();
 
        // Build the help screen information.
        $help[] = 'Your Help Screen';
        $help[] = '';
        $help[] = 'Here is where you put all your help screen information.';
        $help[] = '';
 
        // Print out the help information.
        echo implode("\n", $help);
 
    }
 
    /**
     * Initialize the command line options and arguments.
     *
     * @return void
     * @since 1.0
     */
    private function _initializeOptions()
    {
        // Get the options from the command line argument list and argument values.
        $opts = getopt($this->shortargs /*, $this->longargs*/);
        @$args = (array)$GLOBALS['argv'];
 
        // If the argument value list is not empty, make sure the options are unset.
        if (! empty($args))
        {
            // Iterate over the found options.
            foreach ($opts as $o=>$a)
            {
                // Search for occurrences of the option with no value or with no space betweenoption and value.
                while ($k = array_search('-'.$o.$a, $args))
                {
                    // Remove any found options from the argument value array.
                    if ($k)
                    {
                        unset ($args[$k]);
 
                    }
                }
 
                // Search for remaining occurrences of the option (space between option and value).
                while ($k = array_search('-'.$o, $args))
                {
                    // Remove any found options and values from the argument value array.
                    if ($k)
                    {
                        unset ($args[$k]);
                        unset ($args[$k+1]);
                    }
                }
            }
        }
 
        // Set the options and argument values to internal members.
        $this->options = (object)$opts;
        $this->argv = (array)$args;
 
    }
}
 
// Set error handling.
JError::setErrorHandling(E_ALL, 'echo');
 
// Create the application object.
$app = new JApplicationCLI();
 
// Execute the application.
$app->execute();