dcs/role-provider-orm-bundle
Install Dependencies
Run composer require dcs/role-provider-orm-bundle "~1.0@dev" and ensure dcs/role-core-bundle is also installed (required).
Enable the Bundle
Add to config/bundles.php (Symfony 4+) or AppKernel.php:
DCS\Role\Provider\ORMBundle\DCSRoleProviderORMBundle::class => ['all' => true],
Configure Doctrine
Update your User entity to use the UserRoleCollection trait:
use DCS\Role\Provider\ORMBundle\Model\UserRoleCollection;
#[ORM\Entity]
class User
{
use UserRoleCollection; // Adds role management methods
}
Run Migrations
Execute php bin/console doctrine:migrations:diff and php bin/console doctrine:migrations:migrate to create the role and user_role tables.
First Use Case Assign a role to a user in a controller:
$user->addRole('ROLE_ADMIN'); // Uses the trait's methods
$entityManager->persist($user);
$entityManager->flush();
Role Assignment
Use the trait methods in your User entity:
$user->addRole('ROLE_USER'); // Add single role
$user->addRoles(['ROLE_ADMIN']); // Add multiple roles
$user->removeRole('ROLE_USER'); // Remove role
$user->hasRole('ROLE_ADMIN'); // Check role existence
Role Hierarchy
Leverage DCSRoleCoreBundle's hierarchy system (e.g., ROLE_ADMIN inherits ROLE_USER):
$user->hasRole('ROLE_USER'); // Returns true if user has ROLE_ADMIN
Custom Role Entities
Extend the base Role model (e.g., add metadata):
#[ORM\Entity]
class CustomRole extends \DCS\Role\Provider\ORMBundle\Model\Role
{
#[ORM\Column]
private ?string $description = null;
// Getters/setters...
}
Update the bundle’s Role mapping in config/packages/dcs_role_provider_orm.yaml:
dcs_role_provider_orm:
role_entity: App\Entity\CustomRole
Role-Based Access Control (RBAC) Integrate with Symfony’s security voter:
use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter;
// In a controller or service
$this->denyAccessUnlessGranted('ROLE_ADMIN', $user);
Bulk Role Management Use Doctrine queries for batch operations:
$users = $entityManager->getRepository(User::class)->findBy(['active' => true]);
foreach ($users as $user) {
$user->addRole('ROLE_ACTIVE_USER');
}
$entityManager->flush();
Symfony Forms Dynamically populate role fields:
$builder->add('roles', EntityType::class, [
'class' => Role::class,
'multiple' => true,
'expanded' => true,
]);
APIs (API Platform) Expose role endpoints:
# config/api_platform/resources.yaml
App\Entity\Role:
collectionOperations:
get: ~
itemOperations:
get: ~
Event Listeners Trigger actions on role changes:
// src/EventListener/UserRoleListener.php
class UserRoleListener implements EventSubscriber
{
public static function getSubscribedEvents()
{
return [
UserRoleCollection::ROLE_ADDED => 'onRoleAdded',
];
}
public function onRoleAdded(UserRoleAddedEvent $event)
{
// Send notification, log, etc.
}
}
Testing Mock roles in PHPUnit:
$user = new User();
$user->addRole('ROLE_TEST');
$this->assertTrue($user->hasRole('ROLE_TEST'));
Missing Migrations
doctrine:migrations:migrate post-install.composer.json:
"scripts": {
"post-install-cmd": [
"php bin/console doctrine:migrations:migrate --no-interaction"
]
}
Circular Dependencies
Role or UserRoleCollection may cause conflicts if not properly namespaced.\DCS\Role\Provider\ORMBundle\Model\Role).Role Hierarchy Misconfiguration
ROLE_ADMIN not inheriting ROLE_USER due to incorrect hierarchy setup in DCSRoleCoreBundle.ROLE_USER is defined as a parent role in your hierarchy configuration:
# config/packages/dcs_role_core.yaml
dcs_role_core:
hierarchy:
ROLE_ADMIN: [ROLE_USER]
Performance with Large Role Sets
user_role table:
#[ORM\Table(indexes: [
new Index(['user_id', 'role_id'], name: 'idx_user_role'),
])]
class UserRole {}
Trait Method Overrides
UserRoleCollection methods may break bundle functionality.Query Logging Enable Doctrine debug mode to inspect role-related queries:
# config/packages/dev/doctrine.yaml
doctrine:
dbal:
logging: true
profiling: true
Event Debugging Dump role events in a listener:
public function onRoleAdded(UserRoleAddedEvent $event)
{
dump($event->getUser(), $event->getRole());
}
Common Errors
composer dump-autoload.ROLE_ADMIN vs role_admin).Custom Role Providers
Implement RoleProviderInterface for alternative storage (e.g., Redis):
class RedisRoleProvider implements RoleProviderInterface
{
public function findRoleByName(string $name): ?Role
{
// Custom logic
}
}
Register in services.yaml:
dcs_role_provider_orm.role_provider: '@app.redis_role_provider'
Role Validation
Add constraints to the Role entity:
#[Assert\Length(min: 5, max: 50)]
#[Assert\Regex("/^[A-Z_]+$/")]
private string $name;
Role Serialization Customize serialization for APIs:
#[Groups({"role:read"})]
public function getName(): string
{
return $this->name;
}
Role GUI Management Create a CRUD interface with EasyAdmin or AdminLTE:
# config/packages/easy_admin.yaml
easy_admin:
entities:
App\Entity\Role:
list: [name, description]
form: [name, description]
How can I help you explore Laravel packages today?