我在没有symfony框架的情况下使用symfony的DI。
这是composer.json的一部分
"require" : {
"doctrine/orm" : "*",
"doctrine/migrations" : "^1.5",
"gedmo/doctrine-extensions" : "*",
"symfony/dependency-injection" : "3.4.17",
"symfony/config" : "3.4.17",
"symfony/yaml" : "3.4.17",
"twig/twig" : "^2.0",
"symfony/form": "^3.4",
"symfony/validator": "^3.4",
"symfony/doctrine-bridge": "^3.4",
"symfony/serializer": "^3.4",
"ramsey/uuid": "^3.8",
"ramsey/uuid-doctrine": "^1.5",
"monolog/monolog": "^1.24",
"wazaari/monolog-mysql": "^1.0",
"twilio/sdk": "^5.28",
"mobiledetect/mobiledetectlib": "^2.8",
"symfony/console": "~3.4.23",
"guzzlehttp/guzzle": "^6.3",
"lcobucci/jwt": "^3.2",
"symfony/cache": "^3.4",
"symfony/finder": "^3.4",
"beberlei/DoctrineExtensions": "^1.1",
"symfony/http-foundation": "^3.4",
"sinergi/browser-detector": "^6.1",
"mpdf/mpdf": "~8.0",
"symfony/proxy-manager-bridge": "^3.4"
},
这就是DI容器的构建方式
if (file_exists($containerFile)) {
require_once($containerFile);
$container = new \ProjectServiceContainer();
} else {
$container = new ContainerBuilder();
$container->setProxyInstantiator(new RuntimeInstantiator());
$loader = new YamlFileLoader($container, new FileLocator(__DIR__));
$loader->load(__DIR__.'/../config/services.yml');
$container->compile();
$dumper = new PhpDumper($container);
$containerDir = dirname($containerFile);
file_put_contents($containerFile, $dumper->dump());
}
在config / services.yml中,我已将service标记为lazy
App\Services\MyService:
public: true
lazy: true
当我第一次运行some command
时,它成为MyService
的代理对象,当我第二次运行some command
时,它从{{1} },而且它并不懒惰。
生成的MyService
cache/container.php
实际的问题是此函数内部根本没有使用cache/container.php
变量,因此调用了 protected function getMyServiceService($lazyLoad = true)
的构造函数,但应该延迟,因为$lazyLoad
不使用此方法根本没有服务。