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 Aware Command Bundle Laravel Package

bentools/user-aware-command-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bentools/user-aware-command-bundle
    

    Add to config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3/5):

    return [
        // ...
        BenTools\UserAwareCommandBundle\UserAwareCommandBundle::class => ['all' => true],
    ];
    
  2. Prerequisites Ensure your entities use Gedmo Blameable (e.g., createdBy, updatedBy fields) and Doctrine Extensions are configured.

  3. First Use Case Create a command implementing UserAwareInterface:

    namespace App\Command;
    
    use BenTools\UserAwareCommandBundle\Model\UserAwareInterface;
    use Symfony\Component\Console\Command\Command;
    
    class TestCommand extends Command implements UserAwareInterface
    {
        protected function execute(InputInterface $input, OutputInterface $output): int
        {
            // Entity operations here will auto-populate `createdBy`/`updatedBy`
            return Command::SUCCESS;
        }
    }
    

Implementation Patterns

Workflow Integration

  1. Automatic User Binding

    • The bundle injects a default "System" user (via BenTools\UserAwareCommandBundle\Provider\SystemUserProvider) into Blameable fields.
    • No manual user assignment needed in commands.
  2. Dynamic User Override

    • Pass a user via CLI:
      php bin/console app:test-command --user=admin@example.com
      
    • Override in code (e.g., for testing):
      $this->getApplication()->getKernel()->getContainer()
          ->get('user_aware.command.user_provider')->setUser($userEntity);
      
  3. Custom User Providers

    • Extend BenTools\UserAwareCommandBundle\Provider\UserProviderInterface to fetch users dynamically (e.g., from API tokens):
      class ApiTokenUserProvider implements UserProviderInterface
      {
          public function getUser(): ?User
          {
              return User::findByToken($_ENV['API_TOKEN']);
          }
      }
      
    • Register as a service in services.yaml:
      BenTools\UserAwareCommandBundle\Provider\UserProviderInterface: '@app.api_token_user_provider'
      
  4. Entity-Specific Logic

    • Use UserAwareInterface for commands that modify Blameable entities.
    • For non-Blameable entities, manually inject the user via the provider:
      $user = $this->getContainer()->get('user_aware.command.user_provider')->getUser();
      $entity->setCreatedBy($user);
      

Gotchas and Tips

Pitfalls

  1. Blameable Not Configured

    • If createdBy/updatedBy fields are missing or misconfigured, the bundle silently fails. Verify Gedmo Blameable setup:
      # config/packages/doctrine.yaml
      doctrine:
          orm:
              mappings:
                  gedmo_blameable:
                      type: attribute
                      prefix: Gedmo\Blameable\Entity
                      dir: "%kernel.project_dir%/vendor/gedmo/doctrine-extensions/src/Blameable/Entity"
                      alias: GedmoBlameable
                      is_bundle: false
      
  2. User Provider Conflicts

    • Overriding the default provider requires clearing the Symfony cache:
      php bin/console cache:clear
      
  3. Non-Entity Commands

    • The bundle only affects Doctrine entities. For non-entity operations, manually handle user assignment.

Debugging

  • Check User Binding Log the current user in your command:

    $user = $this->getContainer()->get('user_aware.command.user_provider')->getUser();
    $this->output->writeln(sprintf('Bound user: %s', $user?->getEmail()));
    
  • Verify Provider Inspect the active provider:

    $provider = $this->getContainer()->get('user_aware.command.user_provider');
    $this->output->writeln(get_class($provider));
    

Extension Points

  1. Custom Default User Override the system user in config/packages/user_aware_command.yaml:

    user_aware_command:
        default_user: { id: 1, username: 'default_user', email: 'default@example.com' }
    
  2. Event Listeners Subscribe to UserAwareCommandEvent to modify user logic pre-execution:

    // src/EventListener/UserAwareListener.php
    use BenTools\UserAwareCommandBundle\Event\UserAwareCommandEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class UserAwareListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents(): array
        {
            return [
                UserAwareCommandEvent::NAME => 'onUserAwareCommand',
            ];
        }
    
        public function onUserAwareCommand(UserAwareCommandEvent $event): void
        {
            if ($event->getCommandName() === 'app:critical_command') {
                $event->setUser($this->fetchCriticalUser());
            }
        }
    }
    
  3. Testing Mock the user provider in tests:

    $container = $this->getContainer();
    $container->set('user_aware.command.user_provider', $this->createMock(UserProviderInterface::class));
    
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