在FOSUserBundle中管理用户/角色/组 [英] Managing users/roles/groups in FOSUserBundle

查看:89
本文介绍了在FOSUserBundle中管理用户/角色/组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的CRUD,以管理我正在工作的应用程序的用户/角色/组.为了管理用户,我使用了FOSUserBundle.我想做的事情可以通过几种方式完成:

I am developing a simple CRUD to manage users/roles/groups of the application in which I am working. To manage users I'm using FOSUserBundle. What I want to do can be accomplished in several ways:

  • 将角色分配给组,然后将用户分配给这些组
  • 直接向用户分配角色

但是我不知道如何.我知道FOSUser BaseUser类已经在文档解释了如何在用户和组之间建立ManyToMany关系,但不讨论角色.想到的唯一想法是创建一个实体来管理角色以及用于同一目的的表单,就像您在下面看到的一样:

But I have no idea how. I knew that FOSUser BaseUser class already has a column roles and in the documentation of FOSUser explains how to establish a ManyToMany relationship between users and groups but do not talk anything about roles. The only idea that comes to mind is to create an entity to manage the roles as well as a form for the same purpose, something like what you see below:

角色实体

use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="fos_role")
 * @ORM\Entity(repositoryClass="UserBundle\Entity\Repository\RoleRepository")
 * 
 * @see User
 * @see \UserBundle\Role\RoleHierarchy
 * 
 */
class Role implements RoleInterface
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(name="name", type="string", length=80, unique=true)
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="Role", inversedBy="children")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
     * @var Role[]
     */
    private $parent;

    /**
     * @ORM\OneToMany(targetEntity="Role", mappedBy="parent")
     * @var ArrayCollection|Role[]
     */
    private $children;

    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
     */
    private $users;

    public function __construct($role = "")
    {
        if (0 !== strlen($role)) {
            $this->name = strtoupper($role);
        }

        $this->users = new ArrayCollection();
        $this->children = new ArrayCollection();
    }

    /**
     * @see RoleInterface
     */
    public function getRole()
    {
        return $this->name;
    }

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getUsers()
    {
        return $this->users;
    }

    public function addUser($user, $addRoleToUser = true)
    {
        $this->users->add($user);
        $addRoleToUser && $user->addRole($this, false);
    }

    public function removeUser($user)
    {
        $this->users->removeElement($user);
    }

    public function getChildren()
    {
        return $this->children;
    }

    public function addChildren(Role $child, $setParentToChild = true)
    {
        $this->children->add($child);
        $setParentToChild && $child->setParent($this, false);
    }

    public function getDescendant(& $descendants = array())
    {
        foreach ($this->children as $role) {
            $descendants[spl_object_hash($role)] = $role;
            $role->getDescendant($descendants);
        }
        return $descendants;
    }

    public function removeChildren(Role $children)
    {
        $this->children->removeElement($children);
    }

    public function getParent()
    {
        return $this->parent;
    }

    public function setParent(Role $parent, $addChildToParent = true)
    {
        $addChildToParent && $parent->addChildren($this, false);
        $this->parent = $parent;
    }

    public function __toString()
    {
        if ($this->children->count()) {
            $childNameList = array();
            foreach ($this->children as $child) {
                $childNameList[] = $child->getName();
            }
            return sprintf('%s [%s]', $this->name, implode(', ', $childNameList));
        }
        return sprintf('%s', $this->name);
    }
}

角色表单类型

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RoleType extends AbstractType {

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                ->add('name')
                ->add('parent');
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Tanane\UserBundle\Entity\Role'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'role';
    }    
}

如果是这样的话,将添加到我的用户表单中的内容看起来像这样

If so what would add to my user form would look something like this

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
            ->add('username', 'text')
            ->add('email', 'email')
            ->add('enabled', null, array(
                'label' => 'Habilitado',
                'required' => false
            ))
            ->add('rolesCollection', 'entity', array(
                'class' => 'UserBundle:Role',
                'multiple' => true,
                'expanded' => true,
                'attr' => array('class' => 'single-line-checks')
            ))
            ->add('groups', 'entity', array(
                'class' => 'UserBundle:Group',
                'multiple' => true,
                'expanded' => true,
    ));
}

但是我不知道这是处理角色的正确方法,因为在这种情况下,将在我的数据库中创建一个名为fos_roles的新表,其中处理了用户/角色之间的关系,但是处理了组/之间的关系.角色不参与其中,那便是我有点迷茫,需要经验丰富的人帮助,告诉我并提醒我是否步入正轨,这将使他们实现我在前两点中所解释的内容.有什么建议或帮助吗?您如何处理?

But I do not know if it is the right way to handle the roles since in this case would be creating a new table in my DB called fos_roles where were the relationships between users/roles is handled but relationships between groups/roles stay out of it, then that's where I'm a little lost and need help from the more experienced in that tell me and alert if I'm on track and that would make them to achieve what I explain in the first two points. Any advice or help? How do you deal with this?

推荐答案

Symfony角色

FOSUserBundle处理角色的方式是将它们以序列化格式存储在您看到的roles列中,如下所示:a:1:{i:0;s:10:"ROLE_ADMIN";}.因此,不需要任何其他表或实体^.

The way FOSUserBundle deals with Roles is to store them in the roles column that you've seen, in a serialised format like this: a:1:{i:0;s:10:"ROLE_ADMIN";}. So there's no need for any other tables or entities^.

^ 这与需要明确配置的组相反,它们由单独的表/实体表示,并且确实涉及将用户与数据库中的组相关联.通过组,您可以定义角色的任意集合,然后可以将它们作为离散的捆绑包提供给每个用户.

用户可以是任意数量的角色的成员.它们由以"ROLE_"开头的字符串标识,您可以开始使用新角色.

A User can be a member of any number of Roles. They're identified by strings starting with "ROLE_", you can just start using a new Role.

角色对您的应用程序意味着什么完全取决于您,但是它们是高级工具-用户处于或不处于特定角色.

What the Roles mean for your application is completely up to you, but they're quite a high-level tool - a User is either in a particular Role or they aren't.

您可以通过 Symfony控制台将人员置于角色"中:

You put people in Roles either via the Symfony console:

php app/console fos:user:promote testuser ROLE_ADMIN

或在PHP中:

$user = $this->getUser();
$userManager = $container->get('fos_user.user_manager');
$user->addRole('ROLE_ADMIN');
$userManager->updateUser($user);

您可以测试PHP的成员资格:

And you can test membership in PHP:

$user = $this->getUser();
if ($user->hasRole('ROLE_ADMIN'))
{
    //do something
}

或使用注释:

/**
 * @Security("has_role('ROLE_ADMIN')")
 */
 public function adminAction()
 {
     //...

/**
 * @Security("has_role('ROLE_ADMIN')")
 */
class AdminController
{
    //...

这篇关于在FOSUserBundle中管理用户/角色/组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆