在 Symfony 控制器中访问容器

Access Container in Symfony controllers

我正在 Symfony 组件之上创建一个框架。 http://symfony.com/doc/2.7/create_framework/index.html

我想访问我的控制器中的容器,但我不确定如何以 OOP 方式进行访问。

我目前正在通过 global 访问它,但我相信会有更好的方法来做同样的事情。请参考我的代码块:

#services.yml file
services:
  calendar.model.leapyear:
    class: Calendar\Model\LeapYear

前端控制器文件

<?php

require_once __DIR__.'/../vendor/autoload.php';

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing;
use Symfony\Component\HttpKernel;

$request = Request::createFromGlobals();
$routes = include __DIR__ . '/../src/routes.php';
$container = include __DIR__ . '/../src/app/Container.php';

$context = new Routing\RequestContext();
$matcher = new Routing\Matcher\UrlMatcher($routes, $context);

$controllerResolver = new HttpKernel\Controller\ControllerResolver();
$argumentResolver = new HttpKernel\Controller\ArgumentResolver();

$framework = new Framework($matcher, $controllerResolver, $argumentResolver);
$response = $framework->handle($request);

$response->send();

闰年控制器文件

<?php


namespace Calendar\Controller;

use Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class LeapYearController extends Controller
{

    protected $model;

    public function indexAction(Request $request, $year)
    {
        $this->model = $this->container->get('calendar.model.leapyear');
        if ($this->model->isLeapYear($year)) {
            return new Response('Yep, this is a leap year!');
        }

        return new Response('Nope, this is not a leap year.');
    }
}

基地控制器

<?php

namespace Controller;

use Symfony\Component\DependencyInjection\ContainerAware;

class Controller extends ContainerAware
{
    protected $container;

    public function __construct()
    {
        global $container;
        $this->container = $container;
    }
}

你的基地 class 应该是这样的:

<?php

namespace Controller;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

class Controller implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function getContainer()
    {
        return $this->container;
    }
}

然后在您的控制器中,您可以调用 ContainerAwareTrait 提供的 $this->container 或基本控制器提供的 $this->getContainer()