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

dcs/user-core-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

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

    composer require damianociarla/dcs-user-core-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Damianociarla\DCSUserCoreBundle\DCSUserCoreBundle::class => ['all' => true],
    ];
    
  2. First Use Case: User Creation Inject the factory service into a controller or service:

    use Damianociarla\DCSUserCoreBundle\Factory\UserFactoryInterface;
    
    class UserController extends Controller
    {
        public function __construct(private UserFactoryInterface $userFactory) {}
    
        public function createUser()
        {
            $user = $this->userFactory->create(['email' => 'user@example.com']);
            // Handle the user object (not yet persisted)
        }
    }
    
  3. Event Listeners Configure listeners for dcs_user.manager.save and dcs_user.manager.delete events in config/services.yaml:

    services:
        App\EventListener\UserSaveListener:
            tags:
                - { name: kernel.event_listener, event: dcs_user.save, method: onUserSave }
    

Implementation Patterns

Core Workflows

  1. User Creation & Persistence

    • Use UserFactoryInterface to create a user object.
    • Dispatch the dcs_user.save event to trigger persistence logic:
      $this->eventDispatcher->dispatch(new UserSaveEvent($user));
      
  2. User Deletion

    • Dispatch the dcs_user.delete event with the user ID:
      $this->eventDispatcher->dispatch(new UserDeleteEvent($userId));
      
  3. Repository Integration

    • Implement Damianociarla\DCSUserCoreBundle\Repository\UserRepositoryInterface for custom queries:
      class DoctrineUserRepository implements UserRepositoryInterface
      {
          public function findByEmail(string $email): ?User
          {
              return $this->entityManager->getRepository(User::class)
                  ->findOneBy(['email' => $email]);
          }
      }
      
    • Register the repository as a service:
      services:
          Damianociarla\DCSUserCoreBundle\Repository\UserRepositoryInterface: '@App\Repository\DoctrineUserRepository'
      

Common Patterns

  • Event-Driven Architecture: Extend functionality by listening to dcs_user.* events.
  • Dependency Injection: Prefer injecting UserFactoryInterface or UserRepositoryInterface over instantiating directly.
  • Validation: Validate user data before dispatching events (e.g., using Symfony Validator).

Gotchas and Tips

Pitfalls

  1. No Built-in Persistence

    • The bundle emits events but does not include ORM/ODM logic. You must implement listeners (e.g., Doctrine, MongoDB) to handle persistence.
    • Example missing listener error:
      No listeners found for event "dcs_user.save".
      
  2. Repository Interface Only

    • UserRepositoryInterface is abstract. Implementations must be provided manually (e.g., Doctrine, Eloquent).
    • Avoid calling undefined methods like findAll() unless implemented.
  3. Event Naming Conflicts

    • Ensure event class names (e.g., UserSaveEvent) match the dispatched event names (dcs_user.save).

Debugging Tips

  • Check Event Dispatching: Use Symfony’s EventDispatcher debug tool or add a DEBUG listener to verify events:

    public function onKernelEvent(GetResponseEvent $event)
    {
        if ($event->isMasterRequest()) {
            $this->logger->debug('Dispatched events:', $event->getRequest()->attributes->get('_controller_events'));
        }
    }
    
  • Validate User Data Early: Use Symfony’s ValidatorInterface before dispatching events to avoid partial state issues:

    $errors = $validator->validate($user);
    if (count($errors) > 0) {
        throw new \RuntimeException('User validation failed');
    }
    

Extension Points

  1. Custom User Classes Extend the factory to support custom user entities:

    class CustomUserFactory implements UserFactoryInterface
    {
        public function create(array $data): User
        {
            return new CustomUser($data['email'], $data['name']);
        }
    }
    
  2. Pre/Post-Event Logic Add logic before/after events using event subscribers:

    class UserPreSaveSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                'dcs_user.save' => 'onPreSave',
            ];
        }
    
        public function onPreSave(UserSaveEvent $event)
        {
            $event->getUser()->setCreatedAt(new \DateTime());
        }
    }
    
  3. Repository Decorators Decorate the repository to add cross-cutting concerns (e.g., logging):

    class LoggingUserRepository implements UserRepositoryInterface
    {
        public function __construct(private UserRepositoryInterface $decorated) {}
    
        public function findByEmail(string $email): ?User
        {
            $this->logger->info('Finding user by email', ['email' => $email]);
            return $this->decorated->findByEmail($email);
        }
    }
    

Configuration Quirks

  • Service Overrides: Override default services in config/packages/dcs_user_core.yaml:
    dcs_user_core:
        factory: App\Factory\CustomUserFactory
        repository: App\Repository\CustomUserRepository
    
  • Event Priorities: Use priority in event tags to control listener order:
    tags:
        - { name: kernel.event_listener, event: dcs_user.save, method: onSave, priority: 10 }
    
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
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
spatie/mailcoach-vapor