M2: Debugging Playground
While I’m sure we all agree that your code should live inside an extension, it can be still helpful to interact with something a little more directly or isolated from some other components when debugging. This is where the M1 style “playground script” comes in handy. Note that several things have changed including how models/helpers/etc are accessed, and how the application itself is bootstrapped or more specifically how the object manager is accessed.
//I should live in the root dir next to index.php
require __DIR__ . '/app/bootstrap.php';
//Load the application bootstrapper
$bootstrap = \Magento\Framework\App\Bootstrap::create( BP, $_SERVER );
//Then get the object manager so we can interact with classes and get valid DI
$obj = $bootstrap->getObjectManager();
//Set the application state /** @var \Magento\Framework\App\State $appState */ $appState = $obj->get( 'Magento\Framework\App\State' );
$appState->setAreaCode( \Magento\Framework\App\Area::AREA_FRONTEND );
//Instead of setting a specific code lets use a constant
//A reference of what else is available:
//Get the repository responsible for loading category models
//Just because we're not working in a proper extension
//Doesn't mean we shouldn't load things the right way...
/** @var \Magento\Catalog\Model\CategoryRepository $_categoryRepo */
$_categoryRepo = $obj->get( 'Magento\Catalog\Model\CategoryRepository' );
//See the previous post for a better example of using repos
//Though this particular repo works a little different
//as it only offers the following methods:
//Load by category_id & store_id
$_category = $_categoryRepo->get( 1, 0 );
//Now we have our model...
Originally published at www.davidaaronyoung.com on July 9, 2017.