I am creating roles management in a Symfony 6 project.
Other than a basic USER role (which will be hard-coded), I plan to use other roles that will come from the database. 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 hard-coding anything but USER (which any authenticated member should have).
I am using a DDD approach; maybe it's worth to mention it.
Does anyone have any suggestions? I will appreciate some input regarding this matter.
I assume that using this class is not the best approach.
class UserRoleEnum
{
const ROLE_USER = 'USER';
const ROLE_ADMIN. = 'ADMIN';
const ROLE_SUPER_ADMIN = 'SUPER_AMDIN';
}
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
}