Magento Tutorials Run Magento Code Externally

« Back to Magento Tutorials

Run Magento 1 Code in an External File

If you're working with Magento often you'll find sometimes you need to use Magento code outside of the Magento platform. This can be easily achieved with the following lines of code.

require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();

// Now you can run ANY Magento code you want

// Change 12 to the ID of the product you want to load
$_product = Mage::getModel('catalog/product')->load(12);

echo $_product->getName();

Run Magento 2 Code in an External File

It takes a little more code to do this in Magento but it's still easy enough. Copy the code below into your external file and your own PHP code near the bottom. There's a PHP code comment showing exactly where your code can go.

/*
 *
 * FishPig M2 Bootstrap with useful code
 *
 */
ini_set('display_errors', 1);
error_reporting(E_ALL);

require $__DIR__ . '/app/bootstrap.php';
     
class TestApp extends \Magento\Framework\App\Http implements \Magento\Framework\AppInterface
{
  /**
   * Callback function
   * 
   * @var \Closure
   */
  static $callback;
  
  /*
   * @var string
   */
  protected $areaCode = 'frontend';
  
  /**
   * Run M2 with $callback
   *
   * @param \Closure $callback
   * @return void
   */
  static public function run(\Closure $callback)
  {
    self::$callback = $callback;
    
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $bootstrap->run($bootstrap->createApplication(__CLASS__));
  }

  /**
   * Launch
   *
   * @return
   */
  public function launch()
  {
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    
    $objectManager->get('\Magento\Framework\App\State')->setAreaCode($this->areaCode);

    $objectManager->configure(
      $objectManager->get('\Magento\Framework\ObjectManager\ConfigLoaderInterface')
        ->load($this->areaCode)
    );
    
    call_user_func(self::$callback, $objectManager);

    return $this->_response;
  }
  
  /**
   * Catch an exception
   *
   * @return
   */
  public function catchException(
  	\Magento\Framework\App\Bootstrap $bootstrap, 
  	\Exception $exception
  )
  {
    echo sprintf(
      '<h1>%s</h1><'.'pre>%s<'.'/pre>', $exception->getMessage(), $exception->getTraceAsString()
    );
    
    exit;
  }
}

TestApp::run(function($objectManager) {
  try {
    /**
     *
     * Your PHP code goes here
     *
     */
  }
  catch (\Exception $e) {
    echo $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL . PHP_EOL;
  }
});