j-stam / magento2-shell
添加类似magento 1 shell的功能
README
有时创建新的控制台动作过于繁琐。有时我们只想在我们的magento应用上运行简单的脚本,例如测试一些代码或运行一次性动作。
此包允许您在magento安装上运行动作,就像我们在magento 1上所做的那样。
安装
安装包
composer require j-stam/magento2-shell:*
将此包中的shell文件夹复制到您的magento 2根目录
用法
设置区域代码
默认的区域代码是全局。要使用不同的区域代码,您可以通过覆盖shell脚本中的protected $appAreaCode;来设置它。
可以设置以下区域:
\Magento\Framework\App\Area::AREA_GLOBAL或'global'\Magento\Framework\App\Area::AREA_FRONTEND或'frontend'\Magento\Framework\App\Area::AREA_ADMINHTML或'adminhtml'\Magento\Framework\App\Area::AREA_DOC或'doc'\Magento\Framework\App\Area::AREA_CRONTAB或'crontab'\Magento\Framework\App\Area::AREA_WEBAPI_REST或'webapi_rest'\Magento\Framework\App\Area::AREA_WEBAPI_SOAP或'webapi_soap'\Magento\Framework\App\Area::AREA_GRAPHQL或'graphql'
设置是否安全
例如,删除产品的某些magento动作需要在adminhtml区域执行的同时在安全区域执行。使用protected function setIsSecureArea($isSecure)来设置当前区域是否安全。
实例化对象
- 创建实例:
public function createInstance($type, array $arguments = []) - 获取实例:
public function getInstance($type) - 获取对象管理器:
public function getObjectManager()
使用依赖注入。
依赖注入使用public function getInstance($type)来加载您的依赖。如果您想创建一个新的实例,注入要创建的对象的工厂,并使用其create方法,或者使用createInstance方法代替依赖注入。
protected function di( \Magento\Catalog\Model\Product $product ) { $this->product = $product; }
将数据导出到csv、xml、json
$this->io->writeJson($data, 'filename.json')
从csv、xml、json读取数据
$this->io->readJson('filename.json')
执行sql查询
您可以使用标准的\Magento\Framework\DB\Adapter\AdapterInterface运行sql查询。
$sql = 'SELECT * FROM your_table LIMIT 1'; $result = $this->connection->fetchAll($sql); // or $query = $this->connection->query('SELECT * FROM your_table LIMIT 1'); $result = $query->fetchAll();
将输出写入日志文件
您可以使用monologger将输出写入日志文件。要设置您的日志文件名,覆盖protected $logFileName。当此变量未设置时,您的类名将从PascalCase转换为小写,并用短横线分隔。
要写入日志,请使用protected $logger。
$this->logger->error('Your error message'); $this->logger->info('Your info message'); ...
默认情况下,所有日志文件都放置在{magento_root}/var/log/shell/。要指定您自己的日志文件路径,覆盖protected $logFilePath变量。
将输出写入终端
shell中提供了symfony控制台输出类。这可以通过直接访问protected $consoleOutput来使用。或者,如果您只想写入(一行)您可以使用公共函数write($messages, $newLine = true, $options = OutputInterface::OUTPUT_NORMAL)和writeln($message, $options = OutputInterface::OUTPUT_NORMAL)
$this->writeln('Your line'); $this->write('Your message') $this->write(['Your message', 'Your other message'])
示例脚本
<?php require_once realpath(dirname(__FILE__) . '/../app/bootstrap.php'); class Example extends \Stam\Shell\ShellAbstract { protected $product; /** * Optional function, can be used for dependency injection */ protected function di( \Magento\Catalog\Model\Product $product ) { $this->product = $product; } public function run() { $this->writeln('Hello world!'); $this->logger->debug('Hello world!'); } } $shell = new Example(); $shell->run();