gpt4 book ai didi

php - 如何在 symfony2 全局辅助函数(服务)中访问服务容器?

转载 作者:IT老高 更新时间:2023-10-28 12:09:22 25 4
gpt4 key购买 nike

这个问题开始于我不明白为什么我不能将变量传递给 symfony2 全局帮助函数(服务),但是感谢比我聪明的人,我意识到我的错误是关于尝试从内部使用 security_context没有注入(inject)的类...

这是最终结果,有效的代码。我发现没有更好的方法可以让这对社区有所帮助。

这是您可以从 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
}
}

...定义为这样的服务(在 app/config/config.yml 中)...

#Registering my global helper functions            
services:
biztv.helper.globalHelper:
class: BizTV\CommonBundle\Helper\globalHelper
arguments: ['@service_container']

现在,在我的 Controller 中,我像这样调用这个函数...

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 对象,但它什么也没收到。这是因为在定义服务时,您没有告诉依赖注入(inject)管理器您想要获取容器。将您的服务定义更改为:

services:
biztv.helper.globalHelper:
class: BizTV\CommonBundle\Helper\globalHelper
arguments: ['@service_container']

构造函数应该期待一个 Symfony\Component\DependencyInjection\ContainerInterface 类型的对象;

use Symfony\Component\DependencyInjection\ContainerInterface as Container;

class globalHelper {

private $container;

public function __construct(Container $container) {
$this->container = $container;
}

关于php - 如何在 symfony2 全局辅助函数(服务)中访问服务容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12056178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com