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

darienmh/user-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation: Replace "sonata-project/user-bundle": "^4.1" with "runroom/user-bundle": "4.x-dev" in composer.json and run:

    composer update runroom/user-bundle
    
  2. Enable the Bundle: Add to config/bundles.php:

    Runroom\UserBundle\SonataUserBundle::class => ['all' => true],
    
  3. Database Setup: Run migrations (adjust User entity namespace if needed):

    php bin/console doctrine:schema:update --force
    
  4. First Use Case: Create a basic user registration form by extending SonataUserBundle's controllers or using its built-in CRUD:

    php bin/console generate:sonata:crud User
    

Key Files to Review

  • Configuration: config/packages/sonata_user.yaml (auto-generated after setup).
  • Entities: src/Entity/User.php (default user model).
  • Templates: templates/SonataUserBundle/ (override defaults in templates/).
  • Routing: config/routes/sonata_user.yaml (customize routes if needed).

Implementation Patterns

Common Workflows

1. User Registration & Authentication

  • Default Flow: Use Sonata’s built-in registration controller (/register). Customize via:
    # config/packages/sonata_user.yaml
    sonata_user:
        registration:
            form:
                type: App\Form\RegistrationType  # Extend Sonata\UserBundle\Form\Type\RegistrationType
    
  • Custom Authentication: Override login template (login.html.twig) or extend SonataUserBundle:Security:login route.

2. User Profiles & CRUD

  • Admin Panel: Enable Sonata Admin for users:
    php bin/console generate:sonata:admin User
    
    Customize fields in src/Admin/UserAdmin.php:
    protected function configureListFields(ListMapper $listMapper) {
        $listMapper->add('username');
        $listMapper->add('email');
    }
    
  • Frontend Profiles: Use Sonata’s profile route or build a custom controller:
    // src/Controller/UserController.php
    public function showProfile(User $user) {
        return $this->render('user/profile.html.twig', ['user' => $user]);
    }
    

3. Roles & Permissions

  • Dynamic Roles: Extend User entity to add custom role fields:
    // src/Entity/User.php
    /**
     * @ORM\Column(type="json")
     */
    private $customRoles = [];
    
    Update UserManager to handle serialization:
    // src/Service/UserManager.php
    public function setCustomRoles(User $user, array $roles) {
        $user->setCustomRoles($roles);
        $this->em->persist($user);
        $this->em->flush();
    }
    

4. Integration with Other Bundles

  • FOSUserBridge: If using FOSUserBundle, configure Sonata to bridge with it:
    sonata_user:
        class:
            user: FOS\UserBundle\Entity\User  # Point to FOS User entity
    
  • APIs (API Platform/Symfony UX Turbo): Expose User entity via API:
    # config/packages/api_platform.yaml
    resources:
        App\Entity\User:
            collectionOperations:
                get:
                    method: GET
                    path: /api/users
    

Best Practices

  1. Template Overrides: Copy templates from vendor/runroom/user-bundle/templates/ to templates/SonataUserBundle/ to avoid updates overwriting changes.

  2. Event Listeners: Use Sonata’s events (e.g., sonata.user.register) for custom logic:

    // src/EventListener/UserListener.php
    public function onUserRegister(UserEvent $event) {
        $user = $event->getUser();
        // Add logic (e.g., send welcome email)
    }
    

    Register in services.yaml:

    services:
        App\EventListener\UserListener:
            tags:
                - { name: kernel.event_listener, event: sonata.user.register, method: onUserRegister }
    
  3. Testing: Use Symfony’s WebTestCase for user-related tests:

    public function testRegistration() {
        $client = static::createClient();
        $crawler = $client->request('GET', '/register');
        // Assert form fields, submit, etc.
    }
    

Gotchas and Tips

Pitfalls

  1. PHP Version Quirks:

    • PHP 5.6: Avoid modern PHP features (e.g., typed properties, arrow functions). Use array_column() instead of ArrayObject methods.
    • Deprecated Methods: Sonata 4.x may use methods deprecated in PHP 7.0 (e.g., createFunction()). Patch via:
      // In a custom UserManager
      public function createUser() {
          $user = new User();
          $user->setEnabled(true); // Manually set defaults
          return $user;
      }
      
  2. Doctrine Migrations:

    • Schema Updates: Always back up your database before running doctrine:schema:update. Prefer migrations:
      php bin/console make:migration
      php bin/console doctrine:migrations:migrate
      
    • Custom Fields: If adding fields to User, create a migration:
      php bin/console make:entity User
      # Add field (e.g., bio: string, 255)
      php bin/console make:migration
      
  3. Caching Issues:

    • Clear Cache: After extending entities or templates, run:
      php bin/console cache:clear
      
    • Debug Mode: Enable in .env (APP_DEBUG=1) to see template errors.
  4. Route Conflicts:

    • Sonata’s routes (e.g., /profile) may clash with custom routes. Use _sonata_admin prefix or customize:
      # config/routes/sonata_user.yaml
      sonata_user_profile:
          path: /my-profile
          defaults: { _controller: SonataUserBundle:Profile:show }
      

Debugging Tips

  1. Symfony Profiler: Enable in config/packages/dev/debug.yaml:

    framework:
        profiler: { only_exceptions: false }
    

    Check the "Events" tab for sonata.user.* events.

  2. Logging: Add to config/packages/monolog.yaml:

    handlers:
        sonata:
            type: stream
            path: "%kernel.logs_dir%/sonata.log"
            level: debug
            channels: ["sonata"]
    

    Log Sonata events in a listener:

    $this->logger->debug('User registered', ['user' => $user->getId()]);
    
  3. Common Errors:

    • "Class not found": Ensure Runroom\UserBundle is autoloaded (check composer dump-autoload).
    • Form Errors: Validate custom fields in RegistrationType:
      $builder->add('bio', TextType::class, [
          'constraints' => [new Length(['max' => 500])],
      ]);
      
    • Permission Denied: Verify ROLE_USER is assigned in RegistrationType:
      $user->addRole('ROLE_USER');
      

Extension Points

  1. Custom User Fields: Extend the User entity and update the UserManager:

    // src/Entity/User.php
    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $phoneNumber;
    

    Add to RegistrationType:

    $builder->add('phoneNumber', TextType::class);
    
  2. Custom Validation: Use Symfony’s constraints:

    // src/Entity/User.php
    use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
    
    /**
     * @UniqueEntity(fields="phoneNumber", message="Phone number already taken")
     */
    
  3. API Tokens: Integrate with lexik/jwt-authentication-bundle:

    sonata_user:
        security:
            handler:
                jwt: true  # Enable JWT for API auth
    
  4. Multi-Tenancy: Add tenantId to User and filter queries:

    // src/Repository/UserRepository.php
    public function findByTenant($tenantId) {
        return $this->createQueryBuilder('u')
            ->where('u.tenantId = :tenantId')
            ->setParameter('tenantId', $tenantId)
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui