Magento 1.7 – How to Call a Controller Action Outside Magento

controllersmagento-1.7

We can create php scripts which runs outside magento. And also use magento functionalities by using the following code snippet in it.

define('ROOT', '');
    $mage_php_url = ROOT.'app/Mage.php';

    if (!empty($mage_php_url) && file_exists($mage_php_url) && !is_dir($mage_php_url))
    {
        // Include Magento's Mage.php file.
        require_once ( $mage_php_url );
        umask(0);
        Mage::app();
    }

In these type of scripts we can directly call models, blocks, helpers etc. But how can we call to a controller action in here ? Any suggestions will be appreciated.

Best Answer

Magento isn't really designed to do this, which means you can use controller objects as you would any other object, but there will be complications. Since these methods are meant to be called from an HTTP context, they'll very often do things with the request and response objects, or rely on some bit of session state that just doesn't exist when you're running things from the command line.

That said, the following will work

// require you file        
if(!class_exists('Mage_Customer_AccountController')) //in case the class already exists
{
    require_once('Mage/Customer/controllers/AccountController.php');        
}

// instantiate your controller, using the `Mage:app()` object to grab the required request and response
$controller         = new Mage_Customer_AccountController(
                            Mage::app()->getRequest(),
                            Mage::app()->getResponse()
                        );        

// grab request and response object to manipulate as needed 
// (i.e. controller action expects post variables, etc.)

$request            = $controller->getRequest();
$response           = $controller->getResponse();

//manipulate things as per above

//call the action
$controller->someAction();