Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Role Provider Orm Bundle Laravel Package

dcs/role-provider-orm-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies Run composer require dcs/role-provider-orm-bundle "~1.0@dev" and ensure dcs/role-core-bundle is also installed (required).

  2. Enable the Bundle Add to config/bundles.php (Symfony 4+) or AppKernel.php:

    DCS\Role\Provider\ORMBundle\DCSRoleProviderORMBundle::class => ['all' => true],
    
  3. 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
    }
    
  4. Run Migrations Execute php bin/console doctrine:migrations:diff and php bin/console doctrine:migrations:migrate to create the role and user_role tables.

  5. 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();
    

Implementation Patterns

Core Workflows

  1. 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
    
  2. 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
    
  3. 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
    
  4. 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);
    
  5. 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();
    

Integration Tips

  1. Symfony Forms Dynamically populate role fields:

    $builder->add('roles', EntityType::class, [
        'class' => Role::class,
        'multiple' => true,
        'expanded' => true,
    ]);
    
  2. APIs (API Platform) Expose role endpoints:

    # config/api_platform/resources.yaml
    App\Entity\Role:
        collectionOperations:
            get: ~
        itemOperations:
            get: ~
    
  3. 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.
        }
    }
    
  4. Testing Mock roles in PHPUnit:

    $user = new User();
    $user->addRole('ROLE_TEST');
    $this->assertTrue($user->hasRole('ROLE_TEST'));
    

Gotchas and Tips

Pitfalls

  1. Missing Migrations

    • Issue: Forgetting to run migrations after installation.
    • Fix: Always execute doctrine:migrations:migrate post-install.
    • Tip: Add a post-install script to composer.json:
      "scripts": {
          "post-install-cmd": [
              "php bin/console doctrine:migrations:migrate --no-interaction"
          ]
      }
      
  2. Circular Dependencies

    • Issue: Extending Role or UserRoleCollection may cause conflicts if not properly namespaced.
    • Fix: Use fully qualified class names (e.g., \DCS\Role\Provider\ORMBundle\Model\Role).
  3. Role Hierarchy Misconfiguration

    • Issue: ROLE_ADMIN not inheriting ROLE_USER due to incorrect hierarchy setup in DCSRoleCoreBundle.
    • Fix: Ensure 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]
      
  4. Performance with Large Role Sets

    • Issue: Slow queries when users have many roles.
    • Fix: Add indexes to user_role table:
      #[ORM\Table(indexes: [
          new Index(['user_id', 'role_id'], name: 'idx_user_role'),
      ])]
      class UserRole {}
      
  5. Trait Method Overrides

    • Issue: Overriding UserRoleCollection methods may break bundle functionality.
    • Fix: Prefer composition over inheritance. Extend functionality via events or services.

Debugging

  1. Query Logging Enable Doctrine debug mode to inspect role-related queries:

    # config/packages/dev/doctrine.yaml
    doctrine:
        dbal:
            logging: true
            profiling: true
    
  2. Event Debugging Dump role events in a listener:

    public function onRoleAdded(UserRoleAddedEvent $event)
    {
        dump($event->getUser(), $event->getRole());
    }
    
  3. Common Errors

    • "Class not found": Verify the bundle is enabled and autoloaded. Run composer dump-autoload.
    • "Unknown column": Ensure migrations are up-to-date.
    • "Role not found": Check case sensitivity in role strings (e.g., ROLE_ADMIN vs role_admin).

Extension Points

  1. 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'
    
  2. Role Validation Add constraints to the Role entity:

    #[Assert\Length(min: 5, max: 50)]
    #[Assert\Regex("/^[A-Z_]+$/")]
    private string $name;
    
  3. Role Serialization Customize serialization for APIs:

    #[Groups({"role:read"})]
    public function getName(): string
    {
        return $this->name;
    }
    
  4. 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]
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky