Php 将四个类中的任何一个注入到一个类中
我有一个类(我们称之为Php 将四个类中的任何一个注入到一个类中,php,oop,dependency-injection,Php,Oop,Dependency Injection,我有一个类(我们称之为TestClassA),其中的构造函数如下所示 public function __constructor(SomeInterface $some, AnotherInterface $another, $additionalArgs = null) { // Rest of code } $additionalArgs的值可以来自四个唯一类中的任何一个。每个类都将根据用户的条件集向上面的类添加唯一的查询参数。让我们命名这些类 测试B TestC 测试 睾丸
TestClassA
),其中的构造函数如下所示
public function __constructor(SomeInterface $some, AnotherInterface $another, $additionalArgs = null)
{
// Rest of code
}
$additionalArgs
的值可以来自四个唯一类中的任何一个。每个类都将根据用户的条件集向上面的类添加唯一的查询参数。让我们命名这些类
- 测试B
- TestC
- 测试
- 睾丸
TestC
class,那么他将更改为其余三个类中的任何一个的概率几乎为零。因此,如果我是正确的,如果我使用接口注入(如下面的示例)并添加所有四个类,我将不必要地实例化3个类,因为它们很可能永远不会被使用
public function __constructor(
SomeInterface $some,
AnotherInterface $another,
TestBInterface $testB,
TestCInterface $testC,
TestDInterface $testD,
TestEInterface $testE
) {
// Rest of code
}
我想到的是使用$additionalArgs
属性创建我的TestClassA
,创建所需类的新实例,比如说TestC
,然后将其传递给$additionalArgs
,然后在方法中使用它来获取所需值
范例
$a = new SomeClass;
$b = new AnotherClass;
$c = new TestC;
$d = new TestClassA($a, $b, $c->someMethod());
我的问题是,如何确保传递给$additionalArgs
的值是应传递给此参数的四个类之一的有效实例。我已经尝试在我的方法中使用instanceof
来验证这一点,在本例中为someMethod()
,但条件失败
关于如何解决这个问题,并且仍然“遵守”基本OOP原则,您有什么建议吗?目前您正在传递一个方法的结果,您无法测试它来自哪个类,因此
instanceof
将不起作用。您需要做的是传入对象,测试该对象,然后调用该方法。试试这个:
class TestClassA() {
$foo;
$bar;
$testB;
$testC;
$testD;
$testE;
public function __constructor(Foo $foo, Bar $bar, $test = null)
{
$this->foo = $foo;
$this->bar = $bar;
if ( ! is_null($test))
{
if ($test instanceof TestClassB)
{
$this->testB = $test->someMethod();
}
elseif ($test instanceof TestClassC)
{
$this->testC = $test->someMethod();
}
elseif ($test instanceof TestClassD)
{
$this->testD = $test->someMethod();
}
elseif ($test instanceof TestClassE)
{
$this->testE = $test->someMethod();
}
// Optional else to cover an invalid value in $test
else
{
throw new Exception('Invalid value in $test');
}
}
// Rest of code
}
}
$a = new Foo;
$b = new Bar;
$c = new TestClassC;
$d = new TestClassA($a, $b, $c);
它失败的原因是因为传递的是函数的结果,而不是对象本身。除非传入对象,否则无法验证它是否来自这四个类中的一个。因此,您的意思是,我应该将
$c
传递给$additionalArgs
,然后在我的TestClassA
中检查输入来自何处,以及它是否是我的四个类之一的有效实例。如果是,请以答案的形式回答(如果您愿意,可以添加一个小例子),以便我可以接受。我忘了在我的问题中提到这也是我考虑过的事情。讨厌让我的问题没有答案:-)这正是我想要的。谢谢享受:-)