I am creating roles management in Symfony 6
project.
Other than a basic USER role (which will be hardcoded), plan is that all other roles will come from the database rather than being hardcoded. I know a lot of Symfony guides and tutorials assume you have a limited set of roles you can hardcode, but I don't want to do that here.
Common roles will be USER , ADMIN and SUPERADMIN but I would like to avoid hardcoding anything but USER (which any authenticated member should have).
I am using DDD approach, maybe worth to mention.
Does anyone have any suggestions? I will appreciate some inputs reg this matter.
I assume using:
class UserRoleEnum
{
const ROLE_USER = 'USER';
const ROLE_ADMIN. = 'ADMIN';
const ROLE_SUPER_ADMIN = 'SUPER_AMDIN';
}
..is not the best approach?
CodePudding user response:
If you want to have dynamic roles, then why not just create an entity with roles and add a ManyToMany relationship to the User entity. Using this approach, you will be able to dynamically assign the necessary roles in your admin panel and also more conveniently build your sql requests when necessary.
Role entity
/**
* @ORM\Entity()
* @ORM\Table(name="roles")
*/
class Role
{
/**
* @var int
*
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(name="id", type="integer", unique=true)
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=225, unique=true)
* @Assert\NotBlank()
*/
private $name;
}
User entity
/**
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass=UserRepository::class)
*/
class User implements UserInterface
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToMany(targetEntity="Role",cascade={"persist"})
* @ORM\JoinTable(name="users_roles",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
private $userRoles;
// other properties
}
CodePudding user response:
DUPLICATE : You can find a response here and you can complete whith this SymfonyCast