这不是关于指令(文档是足够的),而是一个事情是如何工作的问题。
Symfony 4自动装配系统允许我们通过简单的键入提示来自动注入服务。
use App\Util\Rot13Transformer;
class TwitterClient
{
public function __construct(Rot13Transformer $transformer)
{
$this->transformer = $transformer;
}
}为了对PHP有更深入的理解,我查看了symfony-bundle源代码,但是找不到“魔术”发生的地方。
Symfony如何防止PHP抗议没有将足够的参数提供给构造函数(或任何使用自动装配的函数)?
发布于 2017-12-03 14:46:54
他们使用“反射”
Symfony如何防止PHP抗议没有向构造函数提供足够的参数
反射允许您检查PHP中其他“事物”的定义。其中包括类--它们的方法,以及这些方法的参数。
<?php
class bar
{
//just a placeholder class
};
$bar = new bar(); //instance of bar
//class to inspect
class foo
{
public function __construct( bar $bar)
{
//do something fancy with $bar
}
}
//get the Reflection of the constructor from foo
$Method = new ReflectionMethod('foo', '__construct');
//get the parameters ( I call them arguments)
$Args = $Method->getParameters();
//get the first argument
$Arg = reset($Args);
//export the argument definition
$export = ReflectionParameter::export(
array(
$Arg->getDeclaringClass()->name,
$Arg->getDeclaringFunction()->name
),
$Arg->name,
true
);
//parse it for the typehint
$type = preg_replace('/.*?(\w+)\s+\$'.$Arg->name.'.*/', '\\1', $export);
echo "\nType: $type\n\n";
var_dump(is_a($bar, $type));产出:
Type: bar
bool(true)你可以看到它,这里
然后,您只需使用is_a()或其他什么来查看“输入”对象是否将bar作为其祖先之一。正如您在这个简化的例子中看到的,如果我们有对象$bar,我们就会知道它作为构造函数的输入非常好,因为它返回true。
我应该指出,这可能不是问这个问题的合适地方,但我可以在我的许多项目中使用它,所以我不介意找出它。而且我从没用过交响乐..。对于解析类型提示的最后一段,特别要感谢这一问题:
也就是说,我大概在10秒内就算出了Regx,出口方法就没那么多了。
这是它的文档的范围。
http://php.net/manual/en/reflectionparameter.export.php
字面意思
public static string ReflectionParameter::export ( string $function , string $parameter [, bool $return ] )发布于 2017-12-03 14:53:44
正如其他人提到的,他们使用反射。如果您想了解Symfony到底是如何做到这一点的,请从autowire()方法这里开始
https://stackoverflow.com/questions/47619285
复制相似问题