如果在方法index注入是重新創(chuàng)建實例,但是通過構造引入則是單例怎么回事。
控制器復用已關閉,目前的解決方案是,控制器構造傳工廠創(chuàng)建。
IndexController.php
<?php
namespace app\controller;
use app\TestInterface;
class IndexController
{
private TestInterface $test;
public function __construct(TestInterface $test)
{
$this->test = $test;
}
public function index()
{
var_dump('控制器 index()');
return $this->test->get();
}
}
dependence.php
<?php
use app\Test;
use app\TestInterface;
return [
TestInterface::class => \DI\autowire(Test::class),
];
控制器生命周期
每個控制器每個進程只會實例化一次,多個進程實例化多次(關閉控制器復用除外,參見控制器生命周期)
控制器實例會被當前進程內多個請求共享(關閉控制器復用除外)
控制器生命周期在進程退出后結束(關閉控制器復用除外)
這個要挖下PHP-DI的源碼,猜測是 dependence.php 定義的依賴都是單例
老哥,通過控制器方法注入是新實例,控制器構造是單例,有點搞不明白。
如果php-di設為單例,控制器方法也是單例,控制器方法的注入是如php-di預期一致的,php-di設置單例就是單例,非單例就是非單例,
唯獨控制器構造是單例,怎么做都是單例。
我換用 Illuminate\Container\Container 了。
<?php
use Illuminate\Container\Container;
$container = new Container();
$dependence = config('dependence');
foreach ($dependence['bind'] as $interface => $implementation) {
$container->bind($interface, $implementation);
}
foreach ($dependence['singleton'] as $interface => $implementation) {
$container->singleton($interface, $implementation);
}
return $container;