这个问题始于我不明白为什么我不能将变量传递给symfony2全局帮助器函数(服务)的原因,但是由于人们比我聪明,我意识到我的错误是关于尝试在没有 没有注射吗...
这是最终结果,该代码有效。 我发现没有更好的方法可以使此方法对社区有所帮助。
这是从symfony2的全局函数或帮助函数中从security_context获取用户和其他数据的方法。
我有以下类和函数:
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
}
}
...定义为这样的服务(在app / config / config.yml中)...
#Registering my global helper functions
services:
biztv.helper.globalHelper:
class: BizTV\CommonBundle\Helper\globalHelper
arguments: ['@service_container']
现在,在控制器中,我像这样调用此函数...
public function createAction($id) {
//do some stuff, transform $id into $entity of my type...
//Check if that container is within the company, and if user has access to it.
$helper = $this->get('biztv.helper.globalHelper');
$access = $helper->hasAccess($entity);