Skip to content

Instantly share code, notes, and snippets.

@theycallmepepper
Created July 10, 2017 03:54
Show Gist options
  • Save theycallmepepper/8ee69bc84a14b5a6c787da650e045879 to your computer and use it in GitHub Desktop.
Save theycallmepepper/8ee69bc84a14b5a6c787da650e045879 to your computer and use it in GitHub Desktop.
Magento 2.x Bootstrapped class example
<?php
//@see https://www.davidaaronyoung.com/m2-debugging-playground-continued/
//I should live in the root dir next to index.php
require __DIR__ . '/app/bootstrap.php';
/**
* Class Playground2
*/
class Playground2 {
/**
* @var \Magento\Framework\App\Bootstrap
*/
protected $bootstrap;
/**
* @var \Magento\Framework\App\State
*/
protected $state;
/**
* @var \Magento\Framework\App\ObjectManager
*/
protected $objManager;
/**
* Playground constructor.
*/
public function __construct()
{
$this->_loadBootstrap();
$this->_loadObjectManager();
$this->_loadAppState();
$this->_setAreaCode();
}
/**
* Bootstrap M2
*/
protected function _loadBootstrap()
{
$this->bootstrap = \Magento\Framework\App\Bootstrap::create( BP, $_SERVER );
}
/**
* Get the object manager so we can interact
* with classes and handle DI
*/
protected function _loadObjectManager()
{
$this->objManager = $this->bootstrap->getObjectManager();
}
/**
* Load the application state class
*/
protected function _loadAppState()
{
$this->state = $this->objManager->get( '\Magento\Framework\App\State' );
}
/**
* Set the proper area code
*
* AREA_GLOBAL
* AREA_FRONTEND
* AREA_ADMIN
* AREA_ADMINHTML
* AREA_DOC
* AREA_CRONTAB
* AREA_WEBAPI_REST
* AREA_WEBAPI_SOAP
*/
protected function _setAreaCode()
{
$this->state->setAreaCode( \Magento\Framework\App\Area::AREA_FRONTEND );
}
/**
* And an example debugging method
*/
public function echoCategoryName()
{
/** @var \Magento\Catalog\Model\Category $_categoryModel */
$_categoryModel = $this->objManager->get( 'Magento\Catalog\Model\Category' );
$_category = $_categoryModel->load( 1 );
echo $_category->getName();
}
}
$playground = new Playground2();
$playground->echoCategoryName();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment