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

User Bundle Laravel Package

docdigital/user-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require docdigital/user-bundle
    

    Enable it in AppKernel.php:

    new DocDigital\UserBundle\DocDigitalUserBundle(),
    
  2. Database Configuration Run migrations to create the required tables:

    php app/console doctrine:schema:update --force
    

    The bundle extends FOSUserBundle, so ensure fos_user is also installed and configured.

  3. First Use Case Create a user with a role hierarchy:

    $user = new \DocDigital\UserBundle\Entity\User();
    $user->setUsername('admin');
    $user->setPlainPassword('secure123');
    $user->setEnabled(true);
    
    $roleAdmin = new \DocDigital\UserBundle\Entity\Role();
    $roleAdmin->setName('ROLE_ADMIN');
    $roleAdmin->setHierarchyLevel(1);
    
    $roleEditor = new \DocDigital\UserBundle\Entity\Role();
    $roleEditor->setName('ROLE_EDITOR');
    $roleEditor->setHierarchyLevel(2);
    
    $user->addRole($roleAdmin);
    $user->addRole($roleEditor);
    
    $em->persist($user);
    $em->persist($roleAdmin);
    $em->persist($roleEditor);
    $em->flush();
    
  4. Key Files to Review

    • Resources/config/routing.yml (for default routes)
    • Entity/User.php (custom user entity)
    • Entity/Role.php (role hierarchy logic)

Implementation Patterns

Common Workflows

Role Hierarchy Management

Use the RoleHierarchy service to check permissions:

$roleHierarchy = $this->get('docdigital_user.role_hierarchy');
if ($roleHierarchy->isGranted('ROLE_ADMIN', $user)) {
    // Grant access
}

Paginated User Listings

Leverage Pagerfanta for paginated user listings:

$users = $this->get('docdigital_user.user_manager')->findAll();
$adapter = new DoctrineORMAdapter($users);
$pagerfanta = new Pagerfanta(new LimitAdapter($adapter, 10));

Custom User Forms

Extend the default FOSUserBundle forms:

# app/config/config.yml
docdigital_user:
    form:
        type: docdigital_user.form.type.user_type

Role-Based Access Control (RBAC)

Use the Voter system for fine-grained access control:

public function vote(TokenInterface $token, $object, array $attributes)
{
    $user = $token->getUser();
    if (!$user instanceof UserInterface) {
        return false;
    }

    $roleHierarchy = $this->get('docdigital_user.role_hierarchy');
    return $roleHierarchy->isGranted('ROLE_EDITOR', $user);
}

Integration Tips

  1. Symfony Security Configure security.yml to use the role hierarchy:

    security:
        access_control:
            - { path: ^/admin, roles: ROLE_ADMIN }
    
  2. Twig Extensions Use the provided Twig extensions for role checks:

    {% if is_granted('ROLE_EDITOR') %}
        <a href="{{ path('edit_content') }}">Edit Content</a>
    {% endif %}
    
  3. Doctrine Lifecycle Callbacks Automate role assignments with Doctrine events:

    $evm->getEventManager()->addEventListener(
        array('prePersist', 'preUpdate'),
        new RoleAssignmentListener()
    );
    
  4. API Integration Use the bundle’s serializers for API responses:

    $serializer = $this->get('jms_serializer');
    $userData = $serializer->serialize($user, 'json');
    

Gotchas and Tips

Pitfalls

  1. Role Hierarchy Conflicts

    • Issue: Circular dependencies in role hierarchy can break permission checks.
    • Fix: Validate hierarchy levels during role creation:
      if ($role->getHierarchyLevel() <= $parentRole->getHierarchyLevel()) {
          throw new \InvalidArgumentException('Invalid hierarchy level');
      }
      
  2. FOSUserBundle Overrides

    • Issue: Custom user classes may conflict with FOSUserBundle’s defaults.
    • Fix: Extend the bundle’s base classes:
      class User extends \DocDigital\UserBundle\Entity\User
      {
          // Add custom fields/methods
      }
      
  3. Pagerfanta Configuration

    • Issue: Pagination may not work if the adapter is misconfigured.
    • Fix: Ensure the adapter matches the query:
      $dql = 'SELECT u FROM DocDigitalUserBundle:User u';
      $query = $em->createQuery($dql);
      $adapter = new DoctrineORMAdapter($query);
      
  4. Doctrine Extensions

    • Issue: stof/doctrine-extensions-bundle may cause conflicts if not configured properly.
    • Fix: Explicitly enable required extensions in config.yml:
      stof_doctrine_extensions:
          orm:
              default:
                  sluggable: true
      

Debugging Tips

  1. Role Hierarchy Debugging Dump the hierarchy structure:

    $roleHierarchy = $this->get('docdigital_user.role_hierarchy');
    dump($roleHierarchy->getHierarchy());
    
  2. Permission Checks Log permission votes for debugging:

    $voter->vote($token, $object, $attributes, $result);
    if (!$result) {
        $this->get('logger')->debug('Permission denied', ['user' => $user->getUsername()]);
    }
    
  3. Form Validation Enable form error logging:

    # app/config/config.yml
    docdigital_user:
        form:
            debug: true
    

Extension Points

  1. Custom Role Providers Implement DocDigital\UserBundle\Provider\RoleProviderInterface for dynamic roles:

    class CustomRoleProvider implements RoleProviderInterface
    {
        public function getRoles(UserInterface $user)
        {
            // Custom logic to fetch roles
        }
    }
    
  2. Event Listeners Extend the bundle’s event system:

    $dispatcher->addListener(
        'docdigital_user.role.pre_save',
        function (RoleEvent $event) {
            // Modify role before save
        }
    );
    
  3. Twig Filters Add custom Twig filters for role checks:

    $twig->addFilter(new \Twig_SimpleFilter('has_role', function ($user, $role) {
        return $this->get('docdigital_user.role_hierarchy')->isGranted($role, $user);
    }));
    
  4. API Resources Extend the bundle’s serializers for custom API responses:

    class UserSerializer extends \FOS\UserBundle\Serializer\UserSerializer
    {
        public function serialize(UserInterface $user, $format, array $context = [])
        {
            $data = parent::serialize($user, $format, $context);
            $data['role_hierarchy'] = $this->getRoleHierarchy($user);
            return $data;
        }
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware