如果在方法index注入是重新創(chuàng)建實(shí)例,但是通過構(gòu)造引入則是單例怎么回事。
控制器復(fù)用已關(guān)閉,目前的解決方案是,控制器構(gòu)造傳工廠創(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),
];
控制器生命周期
每個(gè)控制器每個(gè)進(jìn)程只會(huì)實(shí)例化一次,多個(gè)進(jìn)程實(shí)例化多次(關(guān)閉控制器復(fù)用除外,參見控制器生命周期)
控制器實(shí)例會(huì)被當(dāng)前進(jìn)程內(nèi)多個(gè)請求共享(關(guān)閉控制器復(fù)用除外)
控制器生命周期在進(jìn)程退出后結(jié)束(關(guān)閉控制器復(fù)用除外)
這個(gè)要挖下PHP-DI的源碼,猜測是 dependence.php 定義的依賴都是單例
老哥,通過控制器方法注入是新實(shí)例,控制器構(gòu)造是單例,有點(diǎn)搞不明白。
如果php-di設(shè)為單例,控制器方法也是單例,控制器方法的注入是如php-di預(yù)期一致的,php-di設(shè)置單例就是單例,非單例就是非單例,
唯獨(dú)控制器構(gòu)造是單例,怎么做都是單例。
我換用 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;