![](/img/trans.png)
[英]How to initialize session in symfony controllers and access it in views
[英]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();
LeapYearController文件
<?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;
}
}
您的基類應如下所示:
<?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()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.