Search code examples
phpjoomlajoomla3.0

Joomla How to call controller from external script


I try to launch the functions of a joomla controller from an external script. The beginning of the script works very well but the use of the controller does not. Thank you for your help,

<?php

define('_JEXEC', 1);    

// this file is in a subfolder 'cron' under the main joomla folder
define('JPATH_BASE', realpath(dirname(__FILE__) . '/..'));
require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';

use Joomla\CMS\Factory;

// instantiate application
$app = Factory::getApplication('site');

// database connection
$db = Factory::getDbo();

jimport('joomla.application.component.controller');
JLoader::import('Article', JPATH_ROOT . '/components/com_content/controllers');
$controller = JControllerLegacy::getInstance('Article');
var_dump($controller);

Solution

  • I don't get anything to instantiate a controller from any other place instead of the controller's component.

    So I visit the BaseController class where the getInstance() method lays. You can hack this by setting a task through application input.

    <?php
    
    define('_JEXEC', 1);
    
    // This file is in a subfolder 'cron' under the main joomla folder
    define('JPATH_BASE', realpath(dirname(__FILE__) . '/..'));
    require_once JPATH_BASE . '/includes/defines.php';
    require_once JPATH_BASE . '/includes/framework.php';
    
    use Joomla\CMS\Factory;
    
    // Instantiate application
    $app = Factory::getApplication('site');
    
    // Get the input instance
    $input = $app->input;
    
    // Database connection
    $db = Factory::getDbo();
    
    /**
     * You have to provide a task for getting the controller instance.
     * The `article` is the controller filename as well as the controller class's suffix
     * See the controller class name is `ContentControllerArticle`
     *
     */
    $input->set('task', 'article.');
    
    /**
     * The first argument of the getInstance() function is the type.
     * The type is the component name here.
     * And you have to pass the base_path of the component through the $config argument.
     */
    $controller = JControllerLegacy::getInstance('Content', ['base_path' => JPATH_ROOT . '/components/com_content']);
    
    echo "<pre>";
    print_r($controller);
    echo "</pre>";