MAGENTO 2:“未设置区域代码”

今天,我们要讨论为什么会出现错误“未设置区域代码”。此错误主要发生在模块Cron,Command或Setup Scripts的三个部分中,并在编译或运行setup upgrade命令时发生。在这两种情况下,它都尝试使用您的类的构造函数创建一个对象,但是找不到区号,并且无法加载。

MAGENTO 2中的区号是做什么的?

Magento使用区号来定义给定特定请求上下文的应用程序的哪些部分要加载。系统有七个不同的“区域”,每个区域都有自己的区号:

  • global
  • doc
  • crontab
  • frontend
  • adminhtml
  • webapi_rest
  • webapi_soap

通过Magento \ Framework \ App \ State对象在Magento中设置区号。

我们在Magento 2现金返还扩展中遇到了类似的问题,我们需要重新计算使用cron作业的客户的现金返还折扣。

namespace Scommerce\Custom\Console\Command;
 
 
use Magento\Framework\Console\Cli;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Scommerce\Custom\Cron\CustomProcess;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\App\State;
 
/**
 * Class CustomCommand
 * @package Scommerce\Custom\Console\Command
 */
class CustomCommand extends Command
{
    /**
     * @var CustomProcess
     */
    private $customProcess;
 
    /**
     * @var State
     */
    private $state;
 
    /**
     * Object manager
     *
     * @var ObjectManagerInterface
     */
    protected $objectManager;
 
    /**
     * ProcessSubscriptionsCommand constructor.
     * @param State $state
     * @param ObjectManagerInterface $objectManager
     */
    public function __construct(
        State $state,
        ObjectManagerInterface $objectManager
    ) {
        $this->objectManager = $objectManager;
        $this->state = $state;
        parent::__construct();
    }
 
    protected function configure()
    {
        $this->setName('custom:process')->setDescription('Create custom process');
        parent::configure();
    }
 
    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int|null
     * @throws \Exception
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try{
           $this->state->emulateAreaCode(
            \Magento\Framework\App\Area::AREA_CRONTAB,
            [$this, "executeCallBack"],
            [$input, $output]
          );
        }
        catch(\Exception $e){
        }
    }
 
    protected function executeCallBack(InputInterface $input, OutputInterface $output) {
        $this->customProcess = $this->objectManager->create(CustomProcess::class);
        $this->customProcess->execute();
        return Cli::RETURN_SUCCESS;
    }
}

由于以下原因,以上代码永远不会给您“未设置区域代码”错误-:

1)我们有一个只有两个类objectManagerstate的构造函数。

2)在执行函数中还有emulateAreaCode函数,该函数调用与我们的主要执行函数相同的回调函数。

3)我们还使用objectManager创建依赖类的对象。如果要避免这种情况,请确保确实使用状态类的emulateAreaCode函数为依赖类设置区号。

希望本文对您有所帮助。请留下您的评论,让我们知道您的想法?谢谢。

赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论