我想知道是否有可能通过configureContainer方法直接从AppKernel类在symfony 3.4 MicroKernel app中注册自定义服务,而不是从service.yml文件加载所有服务。
也许是通过ContainerBuilder loadFromExtension方法?
...
class AppKernel extends Kernel
{
use MicroKernelTrait;
public function registerBundles()
{
...
}
protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config.yml');
$c->loadFromExtension('custom_service', [
...
]);
}
...
}
答案 0 :(得分:1)
工作示例:
<?php
use App\LoremIpsum;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
require_once __DIR__ . '/../vendor/autoload.php';
class AppKernel extends Kernel {
use MicroKernelTrait;
public function registerBundles() {
return [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
];
}
protected function configureRoutes(RouteCollectionBuilder $routes) {
$routes->add('/', 'kernel:exampleAction');
}
protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader) {
$c->loadFromExtension('framework', [
'secret' => 'r0tf1.XD',
]);
$c->register(LoremIpsum::class)->setArguments([123, 'ABC'])->setPublic(true);
}
public function exampleAction() {
$obj = $this->getContainer()->get(LoremIpsum::class);
return Response::create((string)$obj);
}
}
$kernel = new AppKernel('dev', true);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
另请参阅:http://symfony.com/doc/3.4/service_container/definitions.html