这个问题始于我不理解为什么我不能将变量传递给symfony2全局帮助函数(服务),但是由于人们比我更亮,我意识到我的错误是试图在类中使用security_context没注射它......
这是最终的结果,代码可行.我发现没有更好的办法让这对社区有帮助.
这是您可以从symfony2中的全局函数或辅助函数中获取security_context中的用户和其他数据的方法.
我有以下类和功能:
<?php
namespace BizTV\CommonBundle\Helper;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
class globalHelper {
private $container;
public function __construct(Container $container) {
$this->container = $container;
}
//This is a helper function that checks the permission on a single container
public function hasAccess($container)
{
$user = $this->container->get('security.context')->getToken()->getUser();
//do my stuff
}
}
Run Code Online (Sandbox Code Playgroud)
...定义为服务(在app/config/config.yml中),就像这样......
#Registering my global helper functions
services:
biztv.helper.globalHelper:
class: BizTV\CommonBundle\Helper\globalHelper
arguments: ['@service_container']
Run Code Online (Sandbox Code Playgroud)
现在,在我的控制器中,我这样调用这个函数......
public function createAction($id) {
//do some stuff, transform $id into $entity of my type...
//Check if that …Run Code Online (Sandbox Code Playgroud)