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 Core Bundle Laravel Package

dcs/role-core-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Prerequisites: Ensure dcs/security-core-bundle is installed (composer require dcs/security-core-bundle "~1.0@dev").
  2. Install the bundle:
    composer require dcs/role-core-bundle "~1.0@dev"
    
  3. Enable in AppKernel.php:
    new DCS\Role\CoreBundle\DCSRoleCoreBundle(),
    
  4. Choose a provider:
    • For ORM-based roles (recommended for most projects):
      composer require dcs/role-provider-orm-bundle "~1.0@dev"
      
    • For array-based roles (simpler, stateless):
      composer require dcs/role-provider-array-bundle "~1.0@dev"
      

First Use Case: Assign a Default Role

Configure a default role in config.yml:

dcs_role_core:
    default_role: ROLE_USER

Inject the RoleManager service in a controller/service:

use DCS\Role\CoreBundle\Manager\RoleManagerInterface;

class UserController extends Controller
{
    public function __construct(RoleManagerInterface $roleManager)
    {
        $this->roleManager = $roleManager;
    }

    public function assignDefaultRole()
    {
        $this->roleManager->assignDefaultRole($user);
    }
}

Implementation Patterns

Core Workflows

  1. Role Assignment:

    • Use RoleManagerInterface to assign roles dynamically:
      $roleManager->assignRole($user, 'ROLE_ADMIN');
      $roleManager->removeRole($user, 'ROLE_USER');
      
    • Batch operations:
      $roleManager->assignRoles($user, ['ROLE_EDITOR', 'ROLE_AUDITOR']);
      
  2. Role Hierarchy (ORM Provider):

    • Define hierarchical roles in your Role entity (e.g., ROLE_ADMIN inherits from ROLE_USER).
    • Leverage the provider’s hasRole() method to check inheritance:
      if ($roleManager->hasRole($user, 'ROLE_USER')) {
          // Includes inherited roles (e.g., ROLE_ADMIN).
      }
      
  3. Authentication Integration:

    • Set a default role during login via AuthenticationSuccessHandler:
      $roleManager->assignDefaultRole($authenticatedUser);
      
  4. Array Provider Use Case:

    • Ideal for stateless or lightweight apps. Define roles in config.yml:
      dcs_role_core:
          provider: array
          roles:
              ROLE_USER: { permissions: [view_content] }
              ROLE_ADMIN: { permissions: [edit_content, delete_content] }
      
    • Access roles via:
      $roleManager->getRole('ROLE_ADMIN')->getPermissions();
      

Integration Tips

  • Symfony Security Component: Use RoleManager alongside AuthorizationChecker for fine-grained access control:
    if ($authorizationChecker->isGranted('ROLE_ADMIN') ||
        $roleManager->hasRole($user, 'ROLE_SUPERVISOR')) {
        // Grant access.
    }
    
  • Doctrine Lifecycle Events: Hook into postPersist/postUpdate to auto-assign roles:
    $entityManager->getEventManager()->addEventListener(
        \Doctrine\ORM\Events::postPersist,
        function ($event) {
            $user = $event->getObject();
            $roleManager->assignDefaultRole($user);
        }
    );
    
  • APIs: Expose role management via API controllers:
    #[Route('/users/{id}/roles', methods: ['POST'])]
    public function assignRole(User $user, Request $request, RoleManagerInterface $roleManager)
    {
        $role = $request->request->get('role');
        $roleManager->assignRole($user, $role);
        return new JsonResponse(['status' => 'assigned']);
    }
    

Gotchas and Tips

Pitfalls

  1. Provider Mismatch:

    • Forgetting to install the required provider bundle (dcs/role-provider-orm-bundle or array) will throw ServiceNotFoundException.
    • Fix: Verify config.yml under dcs_role_core.provider matches the installed provider.
  2. Circular Dependencies:

    • The bundle depends on DCSSecurityCoreBundle. Installing it after DCSRoleCoreBundle may cause autowiring issues.
    • Fix: Install dcs/security-core-bundle first.
  3. ORM Provider Quirks:

    • The Role entity must implement DCS\Role\CoreBundle\Model\RoleInterface. Missing this will break role assignment.
    • Fix: Extend the provided AbstractRole class or implement the interface manually:
      use DCS\Role\CoreBundle\Model\RoleInterface;
      
      class Role implements RoleInterface
      {
          // Implement getRole(), setRole(), etc.
      }
      
  4. Default Role Overrides:

    • Setting default_role in config does not retroactively assign roles to existing users. Use a data fixture or migration:
      $roleManager->assignDefaultRole($existingUser);
      
  5. Array Provider Limitations:

    • Roles are not persisted to a database. Use only for stateless or testing environments.
    • Tip: Combine with DCSRoleProviderORMBundle for production if persistence is needed.

Debugging

  • Role Not Assigned?: Check if the RoleManager is properly injected (use dump($roleManager) to verify). Ensure the user entity is fully persisted before assigning roles (call $entityManager->flush()).

  • Permission Denied: Debug role inheritance with:

    var_dump($roleManager->getRoles($user)); // Shows all assigned + inherited roles.
    

Extension Points

  1. Custom Role Providers: Create your own provider by implementing DCS\Role\CoreBundle\Provider\RoleProviderInterface:

    class CustomRoleProvider implements RoleProviderInterface
    {
        public function assignRole(UserInterface $user, string $role): void
        {
            // Custom logic (e.g., Redis, Elasticsearch).
        }
        // Implement other methods...
    }
    

    Register it in services.yml:

    dcs_role_core.provider: '@custom_role_provider'
    
  2. Role Events: Listen for role changes via Symfony events:

    $eventDispatcher->addListener(
        'dcs_role_core.role_assigned',
        function ($event) {
            // Log or trigger side effects.
        }
    );
    
  3. Role Validation: Add constraints to roles in the ORM provider:

    use Symfony\Component\Validator\Constraints as Assert;
    
    class Role
    {
        #[Assert\NotBlank]
        #[Assert\Length(min: 3)]
        private string $role;
    }
    

Configuration Quirks

  • Case Sensitivity: Role names are case-sensitive (e.g., ROLE_ADMINrole_admin). Standardize naming in your app.
  • Default Role Priority: The default_role config is overridden by explicitly assigned roles. Use assignDefaultRole() sparingly if manual assignment is preferred.
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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
spatie/mailcoach-vapor