Ger*_*ri 3 php typo3 symfony extbase
我在 TYPO3 中做了一个命令,它有参数和依赖注入(DI)。正如我在 symfony 中所理解的,DI 是用 __construct 方法制作的。但在那里我还必须说明我想传递给命令的参数。那么它是如何正确完成的呢?
资料来源:
版本: TYPO3 9.5.5,symfony 4.2.5
假设我想将一个参数传递给命令并从 TYPO3 注入 ObjectManager:
<?php
namespace Vendor\ExtensionName\Command;
use TYPO3\CMS\Extbase\Object\ObjectManagerInterface;
use Symfony\Component\Console\Command\Command;
class SomeCommand extends Command
{
/**
* Object Manager
*
* @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
*/
protected $objectManager;
/**
* @param \TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager
*/
public function __construct(
string $cliParameter,
\TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager)
{
$this->cliParameter = $cliParameter;
$this->objectManager = $objectManager;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我用
bin/typo3 extension_name:someCommand foo
Run Code Online (Sandbox Code Playgroud)
(其中,foo是$cliParameter)
我得到
Uncaught TYPO3 Exception Cannot instantiate interface TYPO3\CMS\Extbase\Object\ObjectManagerInterface
所以我的问题是:我做错了什么?这样做的正确方法是什么?
Symfony 命令与 Extbase 无关。所以你不能使用任何 DI。但是,您仍然可以获取 的实例,ObjectManager然后检索您需要的任何对象:
$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$exampleRepository = $objectManager->get(ExampleRepository::class);
Run Code Online (Sandbox Code Playgroud)
如果一个类不依赖于 Extbase 或者它的 DI,你可以直接用它GeneralUtility::makeInstance()来获取一个实例。