Symfony2-所有控制器的方法


Symfony2 - Methods for all controllers

在开发我的Symfony2应用程序时,我希望在所有控制器中都有可用的方法,就像在RubyonRails中一样。在RoR中,控制器只是在ApplicationController之后继承,这就是放置所有方法的地方。但是Symfony的方式是什么,这里的好做法是什么?

实际上,我想要的功能非常简单,类似于以下内容:

public function showAction()
{
    $user = $this->container->get('security.context')->getToken()->getUser();
}

我可以在这里加载当前用户,我希望在每次操作之前终止此功能,当然,不需要将代码复制到每个控制器中。

您可以为此使用服务。

Acme/DemoBundle/MyService/MyService.php

<?php
namespace Acme/DemoBundle/MyService
class MyService {
   public function myFunction(){
        [...]
   }
}

Acme/DemoBundle/Resources/config/services.yml

services:
    my_service:
        class: Acme/DemoBundle/MyService/MyService

或者.xml版本

Acme/DemoBundle/Resources/config/services.xml

<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd"
>
    <services>
        <service id="my_service" class="Acme'DemoBundle'MyService'MyService">
        </service>
    </services>
</container>

然后在控制器中

Acme/DemoBundle/Controller/MyController.php

$this->container->get("my_service")->myFunction();

要使其在所有捆绑包中可用,只需相应地更新每个捆绑包的服务配置文件。

文档可在此处获得