我在symfony 2.8项目中。另一位开发人员编写了一个Voter来检查用户是否具有特定任务的权限。我已经在控制器中使用此功能而没有任何问题,但现在我正在编写服务以获取动态菜单而我不知道如何访问方法isGranted
:
错误:尝试调用名为" isGranted"的未定义方法。的 类。
namespace NameSpaceQuestion\Question\Service;
use Doctrine\ORM\EntityManager;
class MenuBuilder
{
private $areasTools;
public $menuItems = array();
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function createMenuCourse($course,$mode,$user)
{
$repository = $this->em->getRepository('eBundle:AreasTools');
$areas = $repository->findAll();
//Retrieve every area from the db
$itemsMenu = array();
foreach ($areas as $area) {
//If the user has permissions the area is included in the menu and proceed to check the tools that belong to the current area
if($this->isGranted( $mode,$area,$user ) ){
$itemsMenu[$area->getName()] = array();
$toolsPerCourse = $this->em->getRepository('eBundle:CourseTool')->findByAreaToolAndCourse($area, $course);
foreach ($toolsPerCourse as $toolCourse) {
//If the user has permissions the tool is included in the menu under the respective Area
if( ($this->isGranted( $mode,$toolCourse,$user ) )){
array_push($itemsMenu[$area->getName()], $toolCourse->getName());
}
}
}
}
return $itemsMenu;
}
}
答案 0 :(得分:3)
您必须使用Dependency Injection在MenuBuilder类中获取AuthorizationChecker。您可以在此处阅读:http://symfony.com/doc/current/cookbook/security/securing_services.html
因为看起来你已经注入了EntityManager,只需将AuthorizationChecker添加到你的代码中:
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class MenuBuilder
{
protected $authorizationChecker;
public function __construct(EntityManager $em, AuthorizationCheckerInterface $authorizationChecker)
{
$this->authorizationChecker = $authorizationChecker;
$this->em = $em;
}
function createMenuCourse()
{
if ( $this->authorizationChecker->isGranted('EDIT',$user) ) {
//build menu
}
}
}
答案 1 :(得分:0)
首先要了解的是Symfony基本控制器有许多辅助函数,例如isGranted实现。但是,当然,如果您不在控制器内,那么您无法访问它们。另一方面,查看基类并复制出所需的功能是有益的。
isGranted功能依赖于授权检查服务,您需要将其注入菜单构建器,从而产生如下内容:
class MenuBuilder
{
private $em;
private $authorizationChecker;
public function __construct(
EntityManager $em,
$authorizationChecker // security.authorization_checker
) {
$this->em = $em;
$this->authorizationChecker = $authorizationChecker;
}
protected function isGranted($attributes, $object = null)
{
return $this->authorizationChecker->isGranted($attributes, $object);
}
认真。斯蒂芬在一分钟之内打败了我。必须学会更快地输入。