【发布时间】:2020-06-18 06:50:12
【问题描述】:
考虑这段代码:
<?php namespace App\Services;
use App\Services\AnotherService;
class SomeService {
public function someMethod() {
$anotherService = \App::make(AnotherService::class);
}
}
我的意图是 - 得到一个类对象,它的所有依赖项都已解决。但在这种特定情况下,我希望对象的 __construct 也已执行。我已经尝试过,通过上面的代码,$anotherService 对象的 __construct 方法没有执行。
因此,我可以通过做来实现我所需要的-
$anotherService = \App::make(AnotherService::class);
$anotherService->__construct();
所以我的问题是 - 在实例化对象后每次调用构造方法时可以用单行而不是冗余来完成吗? - 因为这就是 __construct 方法的用途 - 自动执行。但我注意到,由于某种原因,Laravel 的自动依赖解析跳过了 __construct 执行。
请注意,new AnotherService() 对我来说不是一个选项,以及使用 SomeService 类的 __construct 方法。我想在someMethod 方法中创建一个对象。
更新:
AnotherService 类目前没有任何依赖关系。它在__construct 中只有一些随机变量更新,例如:
public function __construct() {
$this->varA = true;
$this->varB = 'Some Value';
}
为什么我需要解析这个类(而不是使用new AnotherClass())? - 仅仅因为我想通过模拟它来测试单元测试中的这个调用。为此,我使用以下代码:
$this->mock(AnotherService::class, function ($mock) {
$mock->shouldReceive('anotherMethod')->andReturn(false);
});
最后我必须调用该方法来检查响应:
$anotherService = \App::make(AnotherService::class);//<-- In this moment $varA and $varB are not set because the __construct did not execute!
$response = $anotherService->anotherMethod();
// Assert...
因此,在这种情况下,例如,如果anotherMethod 将使用这些变量中的任何一个,则测试将不正确,因为它们的值未设置。
【问题讨论】:
-
“Laravel 的自动依赖解析跳过了 __construct 执行。” 我不明白为什么会出现这种情况,因为 laravel 的 IoC 在注入依赖项时会在内部调用
newAnotherService的实现 -
我更新了我的问题。请再次检查以获取更多详细信息。
-
你解决过这个问题吗?我看到了类似的行为,使用
resolve()我的服务的构造函数似乎没有被执行。
标签: php laravel class dependencies construct