Symfony 3.4 微内核定制服务

Symfony 3.4 microkernel custom services

我想知道是否可以通过 configureContainer 方法直接从 AppKernel class 在 symfony 3.4 MicroKernel 应用程序中注册自定义服务,而不是从 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', [
            ...
        ]);
    }

   ...
}

工作示例:

<?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