3

I'm creating a file outside of the public_html folder. In Magento 1.x I could access Magento Core functionality be doing this:

require_once('./app/Mage.php');
Mage::app();

Does anybody know the equivalent in Magento 2?

1
  • Do you plan to create new entry application point inside magento root directory?
    – Max Pronko
    Jan 21, 2016 at 0:38

3 Answers 3

8

You can use Bootstrap to run Application which will return you response object. Here is official example from index.php file:

<?php

require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = 'website2';
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = 'website';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
/** @var \Magento\Framework\App\Http $app *\
$app = $bootstrap->createApplication('Magento\Framework\App\Http');
$bootstrap->run($app);

Hope this helps.

2
  • Hi Max, I'm trying to get started with this but in an external file (say, utilities/test.php) I am redirected to index.php at the Base URL. What do I need to stop or change to prevent this redirection?
    – James
    Mar 31, 2016 at 14:36
  • 2
    so once you do this code, how do you actually do more with it (like get collections, etc)? In other words, do I call methods on $app? do you have to set a store? Stuff like this.
    – ahnbizcad
    Sep 5, 2016 at 4:05
1

Honestly, this is a much better answer IMO.

Demonstrates how to load up a standard Magento 2 abstract class using the bootloader.

How can I bootstrap Magento 2 in a test.php script?

And then, a somewhat more concrete example:

How to load Product or order collection outside project in magento2

0

Check out the below link for a module which exposes the bootstrapped m2 application (and provides helper methods for accessing the layout).

Max is correct -- you need to first Bootstrap Magento (ideally into a new non-http application entry point).

From there you should be able to access the core classes from the object manager. The module is only needed for accessing layout components (which require a bit more magic to get working)

https://www.cadence-labs.com/2017/04/magento-2-load-block-layout-external-file/

Not the answer you're looking for? Browse other questions tagged or ask your own question.