开发我的Symfony2应用程序,我想像Ruby on Rails一样,在所有控制器中都有可用的方法.在RoR控制器中简单地继承之后ApplicationController,这就是你放置所有方法的地方.但Symfony的方式是什么,这里有什么好的做法?
我想要的功能实际上非常简单,类似于:
public function showAction()
{
$user = $this->container->get('security.context')->getToken()->getUser();
}
Run Code Online (Sandbox Code Playgroud)
我可以在这里加载当前用户,我希望在每个操作之前终止此函数,当然不会将代码复制到每个控制器中.
您可以使用此服务.
ACME/DemoBundle /为MyService/MyService.php
<?php
namespace Acme/DemoBundle/MyService
class MyService {
public function myFunction(){
[...]
}
}
Run Code Online (Sandbox Code Playgroud)
ACME/DemoBundle /资源/配置/ services.yml
services:
my_service:
class: Acme/DemoBundle/MyService/MyService
Run Code Online (Sandbox Code Playgroud)
或.xml版本
ACME/DemoBundle /资源/配置/的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>
Run Code Online (Sandbox Code Playgroud)
然后在控制器中
极致/ DemoBundle /控制器/ MyController.php
$this->container->get("my_service")->myFunction();
Run Code Online (Sandbox Code Playgroud)
要使其在所有捆绑包中可用,只需相应地更新每个捆绑包的服务配置文件.
文档可在此处获得