[我目前正在学习magento 2,例如此处的自定义路线:
https://devdocs.magento.com/guides/v2.3/extension-dev-guide/routing.html
/**
* @param RequestInterface $request
* @return ActionInterface|null
*/
public function match(RequestInterface $request): ?ActionInterface
{
$identifier = trim($request->getPathInfo(), '/');
if (strpos($identifier, 'learning') !== false) {
$request->setModuleName('routing');
$request->setControllerName('index');
$request->setActionName('index');
$request->setParams([
'first_param' => 'first_value',
'second_param' => 'second_value'
]);
return $this->actionFactory->create(Forward::class, ['request' => $request]);
}
我的问题是关于这条线的
return $this->actionFactory->create(Forward::class, ['request' => $request]);
它为create方法的2个参数提供Forward :: class和一个包含请求信息的数组,但是ActionFactory create方法的实现是这个
/**
* Create action
*
* @param string $actionName
* @return ActionInterface
* @throws \InvalidArgumentException
*/
public function create($actionName)
{
if (!is_subclass_of($actionName, \Magento\Framework\App\ActionInterface::class)) {
throw new \InvalidArgumentException(
'The action name provided is invalid. Verify the action name and try again.'
);
}
return $this->_objectManager->create($actionName);
}
而且似乎create方法只需要一个参数,我确实通过删除响应数组['request' => $request]
对此进行了测试,但它仍然有效!
那么,为什么magento文档和许多其他教程放置两个参数?
[当您调用this->actionFactory->create
时,它随后调用this->_objectManager->create
,它带有两个参数:类型和要传递给新创建对象的构造函数的可选参数数组。
以下是ObjectManagerInterface
的相关部分:https://github.com/magento/magento2/blob/2.3/lib/internal/Magento/Framework/ObjectManagerInterface.php
interface ObjectManagerInterface
{
/**
* Create new object instance
*
* @param string $type
* @param array $arguments
* @return mixed
*/
public function create($type, array $arguments = []);
}
我不懂PHP。但是,看来actionFactory->create
函数将传递给它的所有参数视为一个实体,然后将它们传递给objectManager->create
函数。
我向我自己证明了这在PHP中是可能的,这里:https://www.tehplayground.com/ByxUV6Q4Sk284wqJ
注:即使仅传递一个参数,它也起作用的原因是arguments数组是可选的。默认为空数组。