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

friendsofsymfony/user-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require friendsofsymfony/user-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        FriendsOfSymfony\UserBundle\FOSUserBundle::class => ['all' => true],
    ];
    
  2. Configure Database: Update config/packages/fos_user.yaml (auto-generated) to match your Doctrine setup:

    fos_user:
        db_driver: orm  # or 'mongodb' if using ODM
        firewall_name: main
        user_class: App\Entity\User
    
  3. Generate User Entity:

    php bin/console make:user
    

    (Follow prompts to customize fields like email, roles, etc.)

  4. First Use Case: Register a new user via the built-in controller:

    php bin/console fos:user:register john doe john@example.com password123
    

Implementation Patterns

Core Workflows

  1. User Registration:

    • Extend FOS\UserBundle\Form\Type\RegistrationFormType to add custom fields.
    • Override the registration template (templates/FOSUserBundle/Registration/register.html.twig).
    • Example:
      // src/Form/RegistrationFormTypeExtension.php
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $builder->add('custom_field', TextType::class);
      }
      
  2. Password Reset:

    • Use the built-in FOS\UserBundle\Controller\ResetPasswordController.
    • Customize the reset token TTL in config:
      fos_user:
          reset_token_ttl: 86400  # 1 day in seconds
      
  3. Authentication Integration:

    • Configure security.yaml to use FOSUser’s provider:
      security:
          providers:
              fos_userbundle:
                  id: fos_user.user_provider.username_email
          firewalls:
              main:
                  form_login:
                      provider: fos_userbundle
      
  4. Profile Management:

    • Extend FOS\UserBundle\Form\Type\ProfileFormType for custom profile fields.
    • Redirect after profile updates in UserManager:
      // src/EventListener/UserEvents.php
      public function onUserUpdated(UserEvent $event)
      {
          $event->getUser()->setLastLogin(new \DateTime());
      }
      

Common Integrations

  • Doctrine Lifecycle Callbacks:

    // src/Entity/User.php
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity(repositoryClass: UserRepository::class)]
    class User implements UserInterface
    {
        #[ORM\PrePersist]
        public function setCreatedAt(): void
        {
            $this->createdAt = new \DateTime();
        }
    }
    
  • Event Subscribers: Listen to FOSUserEvents::REGISTRATION_COMPLETED to send welcome emails:

    // src/EventListener/RegistrationListener.php
    public static function getSubscribedEvents()
    {
        return [
            FOSUserEvents::REGISTRATION_COMPLETED => 'onRegistrationCompleted',
        ];
    }
    
    public function onRegistrationCompleted(FilterUserResponseEvent $event)
    {
        $user = $event->getUser();
        // Send email via MailerInterface
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warnings:

    • FOSUserBundle is legacy (no active maintenance). Avoid in new projects.
    • Use Symfony’s SecurityBundle + custom User entity instead (e.g., via make:auth).
  2. Configuration Overrides:

    • Custom config in fos_user.yaml must merge with defaults. Example:
      # Incorrect (overwrites entirely)
      fos_user:
          user_class: App\Entity\CustomUser
      
      # Correct (extends defaults)
      fos_user:
          user_class: App\Entity\CustomUser
          from_email:
              address: no-reply@example.com
      
  3. Token Service Quirks:

    • Reset tokens are single-use by default. Regenerate if needed:
      $user->setResetToken($userManager->generateResetToken());
      $userManager->updateUser($user);
      
  4. ORM vs. ODM:

    • MongoDB ODM support is limited. Prefer Doctrine ORM for complex queries.

Debugging Tips

  1. Check User Events: Enable debug logging for fos_user events:

    # config/packages/dev/monolog.yaml
    handlers:
        fos_user:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.fos_user.log"
            level: debug
            channels: ["fos_user"]
    
  2. Token Validation:

    • Reset tokens expire after fos_user.reset_token_ttl. Test with:
      php bin/console fos:user:reset-password john@example.com
      
  3. Form Validation:

    • Custom validation fails silently. Check constraints in User entity:
      #[Assert\NotBlank]
      #[Assert\Email]
      private ?string $email = null;
      

Extension Points

  1. Custom User Fields:

    • Add fields to User entity and extend forms:
      // src/Form/Type/UserType.php
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $builder->add('avatar', FileType::class);
      }
      
  2. Override Controllers:

    • Extend FOS\UserBundle\Controller\RegistrationController for custom logic:
      // src/Controller/CustomRegistrationController.php
      class CustomRegistrationController extends RegistrationController
      {
          public function registerAction()
          {
              // Custom logic before/after registration
              return parent::registerAction();
          }
      }
      
  3. API Integration:

    • Use UserManager in API controllers:
      public function updateProfile(UserManagerInterface $userManager, Request $request)
      {
          $user = $userManager->findUserBy(['id' => $request->attributes->get('id')]);
          // Update user data
          $userManager->updateUser($user);
      }
      
  4. Testing:

    • Mock UserManager in tests:
      $userManager = $this->createMock(UserManagerInterface::class);
      $userManager->expects($this->once())
          ->method('createUser')
          ->willReturn($user);
      
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