如何在 symfony2 全局辅助函数(服务)中访问服务容器?
这个问题开始时我不明白为什么我不能将变量传递给 symfony2 全局辅助函数(服务),但多亏了比我聪明的人,我意识到我的错误是试图从内部使用 security_context没有注入它的类所以...
This question started out with me not understanding why I couldn't pass variables to a symfony2 global helper function (service), but thanks to people brighter than I, I realized my error was about trying to use the security_context from within a class that didn't have it injected so...
这是最终的结果,有效的代码.我发现没有更好的方法可以让这对社区有所帮助.
This is the final result, the code that works. I found no better way of making this helpful to the comunity.
这是您如何从 symfony2 中的全局函数或辅助函数中的 security_context 中获取用户和其他数据的方法.
This is how you can get the user and other data from security_context from within a global function or helper function in symfony2.
我有以下类和函数:
<?php
namespace BizTVCommonBundleHelper;
use SymfonyComponentDependencyInjectionContainerInterface 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 中)...
...defined as a service (in app/config/config.yml) like this...
#Registering my global helper functions
services:
biztv.helper.globalHelper:
class: BizTVCommonBundleHelperglobalHelper
arguments: ['@service_container']
现在,在我的控制器中,我像这样调用这个函数......
Now, in my controller I call on this function like this...
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);
我假设第一个错误(未定义的属性)发生在您添加属性和构造函数之前.然后你得到了第二个错误.另一个错误意味着您的构造函数希望接收一个 Container 对象,但它什么也没收到.这是因为在定义服务时,您没有告诉依赖注入管理器您想要获取容器.将您的服务定义更改为:
I assume that the first error (undefined property) happened before you added the property and the constructor. Then you got the second error. This other error means that your constructor expects to receive a Container object but it received nothing. This is because when you defined your service, you did not tell the Dependency Injection manager that you wanted to get the container. Change your service definition to this:
services:
biztv.helper.globalHelper:
class: BizTVCommonBundleHelperglobalHelper
arguments: ['@service_container']
然后构造函数应该期望一个 SymfonyComponentDependencyInjectionContainerInterface 类型的对象;
The constructor should then expect an object of type SymfonyComponentDependencyInjectionContainerInterface;
use SymfonyComponentDependencyInjectionContainerInterface as Container;
class globalHelper {
private $container;
public function __construct(Container $container) {
$this->container = $container;
}