gpt4 book ai didi

Symfony2访问服务中的用户和原则

转载 作者:行者123 更新时间:2023-12-04 05:18:30 25 4
gpt4 key购买 nike

我正在大量的 Controller 操作中运行等效于此代码的代码,基本上它会捕获用户的用户名,并且如果该用户名附加到博客实体,它将允许用户查看博客实体:

    $em = $this->getDoctrine()->getManager();
$user = $this->get('security.context')->getToken()->getUser();
$entities = $em->getRepository('MySiteBundle:Blog')->findBy(array('user' => $user));

return $this->render('MySiteBundle:Blog:index.html.twig', array(
'entities' => $entities,

我想将其移入服务,以便减少代码重复。我想避免在 Controller 中执行尽可能多的逻辑。

话虽这么说,我不确定如何访问服务中的用户 session 和学说。

这是我的services.yml:
mysite.user.blog:
class: MySite\SiteBundle\Services\BlogUser

这就是我试图在 Controller 中调用它的方式:
public function testAction() {
$response = $this->get('mysite.user.blog');
return new Response($response);
}

我确实尝试过使用事件 subscriber/listener标记,但这似乎无法完成我想要的任务。

这是我完全可怕的服务尝试。如果不使用构造函数,我将无法获得任何响应。
namespace MySite\SiteBundle\Services;

use MySite\SiteBundle\Entity\Blog;

class BlogUser {

protected $entities;

public function __construct(){
$em = $this->getDoctrine()->getManager();
$user = $this->get('security.context')->getToken()->getUser();
$this->entities = $em->getRepository('MySiteBundle:Blog')->findBy(array('user' => $user));
}
}

我要用完全错误的方式去做吗?有没有更好的方法我想念吗?

编辑/回答:

修改了我的命名约定:
//services.yml
mysite.user.blog.entities:
class: Mysite\SiteBundle\Services\BlogUser
arguments: ["@doctrine.orm.entity_manager", "@security.context"]

在 Controller Action 中:
$userEntities = $this->get('mysite.user.blog.entities');
$entities = $userEntities->getEntities();

在服务本身中:
class BlogUser {

protected $entities;

public function __construct($em, $securityContext){
$user = $securityContext->getToken()->getUser();
$this->entities = $em->getRepository('MySiteBundle:Blog')->findBy(array('user' => $user));
}
public function getEntities(){
return $this->entities;
}
}

仍然需要两行来获取 Controller 中的$ entities变量,但这比一遍又一遍定义相同的东西要好得多。

最佳答案

自Symfony 2.6以来不推荐使用“Security.context”

After some community discussions, it was decided that SecurityContext gives too many dependencies to retrieve a simple Token/User object. That's why, starting with Symfony 2.6, thesecurity.context service has been deprecated and split into two new services:security.authorization_checker and security.token_storage.



Source

因此,执行此操作的新方法是,首先将服务配置为:
mysite.user.blog:
class: MySite\SiteBundle\Services\BlogUser
arguments: ["@doctrine.orm.entity_manager", "@security.token_storage"]

然后在服务类的构造函数中:
class BlogUser
{
protected $user;
protected $entities;

public function __construct(EntityManager $em, TokenStorage $tokenStorage)
{
$this->user = $tokenStorage->getToken()->getUser();
$this->entities = $em->getRepository('MySiteBundle:Blog')->findBy(array('user' => $user));
}
}

关于Symfony2访问服务中的用户和原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18223988/

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