Skip to content

Instantly share code, notes, and snippets.

@vasilii-b
Last active September 16, 2024 13:16
Show Gist options
  • Save vasilii-b/6a50a6c35a2bdc2f2afff38daa2a7550 to your computer and use it in GitHub Desktop.
Save vasilii-b/6a50a6c35a2bdc2f2afff38daa2a7550 to your computer and use it in GitHub Desktop.
Shows example of usage of Magento 2 emulate area code
<?php
declare(strict_types=1);
namespace Vendor\Module\Service;
use Magento\Framework\App\Area as AppArea;
use Magento\Framework\App\State as AppState;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\NoSuchEntityException;
/**
* Class SetCategoriesNavigationSettingsService
*/
class SetCategoriesNavigationSettingsService
{
/**
* @var AppState
*/
private $appState;
/**
* @var UpdateCategoryService
*/
private $updateCategoryService;
/**
* Class constructor
*
* @param AppState $appState
* @param UpdateCategoryService $updateCategoryService
*/
public function __construct(
AppState $appState,
UpdateCategoryService $updateCategoryService
) {
$this->appState = $appState;
}
/**
* Example on how to emulate area and pass some method as callback
*
* @return void
*/
public function execute(): void
{
// Method #1 to call some other stuff
$this->appState->emulateAreaCode(
AppArea::AREA_ADMINHTML,
[$this->updateCategoryService, 'execute'],
[$param1, $param2]
);
// Method #2 to call some other stuff
$categoryId = 100;
$service = $this->updateCategoryService;
$this->appState->emulateAreaCode(
AppArea::AREA_ADMINHTML,
function() use ($service, $categoryId) {
$service->execute($categoryId);
}
);
}
}
@koentjeh
Copy link

Thank you kindly for your example. Would you also care to explain when and why to emulate an area? That is still unclear to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment