个性化阅读
专注于IT技术分析

如何在Symfony 3中使用FOSUserBundle向用户添加角色

本文概述

用户角色是预定义的角色, 它允许用户在你的应用程序中执行不同的活动。使用用户权限时, 有很多要处理的地方(此处未提及), 为了使用户和开发人员更容易使用, 角色的实现是用户的一项有用(也是基本要求)的功能系统。

在本文中, 你将学习如何在Symfony 3中使用FOSUserBundle向用户添加角色。

Doctrine

你可以使用用户对象的addRole方法向用户添加角色。

<?php

namespace ourcodeworld\adminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class AdminController extends Controller
{
    public function indexAction()
    {
        // Retrieve entity manager of doctrine
        $em = $this->getDoctrine()->getManager();

        // Search for the UserEntity, retrieve the repository
        $userRepository = $em->getRepository("myBundle\Entity\User");
        // or $userRepository = $em->getRepository("myBundle:User");

        $user = $userRepository->findOneBy(["username" => "AnyUsername"]);
        
        // Add the role that you want !
        $user->addRole("ROLE_ADMIN");

        // Save changes in the database
        $em->persist($user);
        $em->flush();
    }
}    

使用fos_user.user_manager

你可以使用fos用户管理器创建用户, 该服务可以从容器中检索(控制器中的$ this-> get(‘serviceName’)或容器中任何其他位置的$ container-> get(”)在上下文中)。

<?php

namespace ourcodeworld\adminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class AdminController extends Controller
{
    public function indexAction()
    {
        $userManager = $this->get('fos_user.user_manager');

        // Use findUserby, findUserByUsername() findUserByEmail() findUserByUsernameOrEmail, findUserByConfirmationToken($token) or findUsers()
        $user = $userManager->findUserBy(['id' => 1]);
        
        // Add the role that you want !
        $user->addRole("ROLE_ADMIN");
        // Update user roles
        $userManager->updateUser($user);
    }
}

在用户类别中

你还可以在每次注册用户时在User Entity类的构造函数中设置角色:

<?php
// src/Acme/UserBundle/Entity/User.php

namespace myBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    public function __construct()
    {
        parent::__construct();
        
        // Add role
        $this->addRole("ROLE_ADMIN");
    }
}

$ this的上下文将特别是BaseUser。

使用FOSUserBundle命令行工具

默认情况下, 实现FOSUserBundle的symfony应用程序将自动访问此捆绑软件的命令行工具。该工具提供了一个有用的命令, 即fos:user:promote命令, 可用于向用户添加角色。此命令使你可以向用户添加角色或使该用户成为超级管理员:

php bin/console fos:user:promote username ROLE_ADMIN

玩得开心 !

赞(0)
未经允许不得转载:srcmini » 如何在Symfony 3中使用FOSUserBundle向用户添加角色

评论 抢沙发

评论前必须登录!