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

Ezplatform User Laravel Package

ezsystems/ezplatform-user

User management bundle for eZ Platform/EzPlatform: handles users, roles and permissions, authentication and related services. Integrates with the repository and security layer to manage accounts, groups, and access control in eZ-based apps.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require ezsystems/ezplatform-user:^2.3.12

Ensure your project extends ezsystems/ezplatform-user in composer.json under require.

  1. Service Configuration Add the bundle to config/bundles.php:

    return [
        // ...
        EzSystems\EzPlatformUserBundle\EzSystemsEzPlatformUserBundle::class => ['all' => true],
    ];
    
  2. First Use Case: User Creation with Generator Workflow Leverage the new reusable generator workflow for streamlined user creation:

    use EzSystems\EzPlatformUserBundle\Service\UserGenerator;
    
    public function __construct(private UserGenerator $userGenerator) {}
    
    public function generateUser()
    {
        $user = $this->userGenerator->generate([
            'email' => 'john.doe@example.com',
            'password' => 'securePassword123',
            'roles' => ['ROLE_USER'],
            'firstName' => 'John',
            'lastName' => 'Doe',
        ]);
        $this->userService->saveUser($user);
    }
    

    Note: The UserGenerator replaces manual entity construction for common use cases.

  3. Key Classes to Explore

    • UserGenerator: New reusable workflow for user creation (replaces manual UserService calls for standard cases).
    • UserService: Core interface for advanced CRUD operations (still required for custom logic).
    • User: Entity representing users (extends ezsystems/ezplatform-kernel User).
    • UserRepository: For querying users (e.g., findByEmail()).

Implementation Patterns

Workflows

1. User Registration Flow (Updated)

// 1. Use the new generator for standard cases
$user = $this->userGenerator->generate([
    'email' => 'john.doe@example.com',
    'password' => 'plainPassword123', // Automatically hashed
    'roles' => ['ROLE_USER'],
    'customFields' => ['department' => 'Marketing'],
]);

// 2. Save and trigger events
$userService->saveUser($user);
event(new UserRegisteredEvent($user));

2. Role Management (Unchanged)

// Add role to existing user
$user = $userService->loadUserByUsername('john.doe@example.com');
$user->addRole('ROLE_ADMIN');
$userService->saveUser($user);

3. Bulk User Generation (New)

// Generate 10 users with reusable template
$users = $userGenerator->generateBulk(10, [
    'emailTemplate' => 'user{index}@example.com',
    'password' => 'defaultPass123',
    'roles' => ['ROLE_USER'],
]);

foreach ($users as $user) {
    $userService->saveUser($user);
}

4. API-Driven User Management (Unchanged)

// Export users to CSV (unchanged)
$users = $userRepository->findAll();
$csv = new League\Csv\Writer(fopen('php://output', 'w'));
$csv->insertOne(['Email', 'Roles']);
foreach ($users as $user) {
    $csv->insertOne([$user->getEmail(), implode(', ', $user->getRoles())]);
}

Integration Tips

Laravel-Specific Adaptations

  1. Service Provider Binding (Updated) Bind both UserService and UserGenerator in AppServiceProvider:

    $this->app->bind(UserGenerator::class, function ($app) {
        return new UserGenerator(
            $app->make(UserService::class),
            $app->make(UserPasswordHasherInterface::class)
        );
    });
    
  2. Event Listeners (Unchanged) Listen to UserRegisteredEvent in Laravel’s event system:

    Event::listen(UserRegisteredEvent::class, function (UserRegisteredEvent $event) {
        // Send welcome email, log activity, etc.
    });
    
  3. Query Builder Extensions (Unchanged) Extend the UserRepository to add custom methods:

    class CustomUserRepository extends UserRepository
    {
        public function findActiveUsers()
        {
            return $this->createQueryBuilder('u')
                ->where('u.enabled = :enabled')
                ->setParameter('enabled', true)
                ->getQuery()
                ->getResult();
        }
    }
    

Common Integrations (Updated)

  • Laravel Fortify: Replace User model with ezsystems/ezplatform-user’s User and use UserGenerator for registration:
    // In Fortify's CreateNewUser action
    $user = $userGenerator->generate($request->only(['email', 'password']));
    $userService->saveUser($user);
    
  • Laravel Nova: Extend Nova’s Resource to work with User entity (unchanged).
  • Laravel Passport: Use UserService for OAuth user resolution (unchanged).

Gotchas and Tips

Pitfalls

  1. Password Hashing Mismatch (Updated)

    • The UserGenerator automatically handles password hashing. Avoid manually hashing passwords when using the generator:
      // ❌ Avoid this with UserGenerator
      $hashed = $passwordHasher->hashPassword($user, 'plainPassword');
      
      // ✅ Correct (let UserGenerator handle it)
      $user = $userGenerator->generate(['password' => 'plainPassword']);
      
  2. Role Hierarchy Conflicts (Unchanged)

    • Roles like ROLE_ADMIN may override ROLE_USER. Test role inheritance explicitly.
  3. Entity Manager Detachment (Unchanged)

    • Avoid detaching entities between requests (e.g., in queues). Reattach with:
      $entityManager->persist($user);
      $entityManager->flush();
      
  4. Custom Fields Not Persisted (Updated)

    • Ensure custom fields are included in the UserGenerator payload:
      $user = $userGenerator->generate([
          'email' => 'test@example.com',
          'customFields' => [  // Required for non-standard fields
              'department' => 'Engineering',
              'hireDate' => '2023-01-01',
          ],
      ]);
      

Debugging

  1. User Not Found Exceptions (Unchanged)

    • Check if the UserRepository is properly injected. Override loadUserByUsername() to log queries.
  2. Password Reset Issues (Unchanged)

    • Verify the UserPasswordHasherInterface is configured in Symfony’s security.yaml.
  3. Generator Validation Failures (New)

    • The UserGenerator validates input. Check for errors:
      try {
          $user = $userGenerator->generate(['email' => 'invalid-email']);
      } catch (InvalidArgumentException $e) {
          \Log::error("Generator validation failed: " . $e->getMessage());
      }
      
  4. Bulk Generation Issues (New)

    • Validate bulk generation templates:
      $users = $userGenerator->generateBulk(5, [
          'emailTemplate' => 'user{index}@example.com', // Must include {index}
          'password' => 'securePass123',
      ]);
      

Extension Points

  1. Custom User Fields (Updated) Extend the User entity and update the UserGenerator:

    class CustomUserGenerator extends UserGenerator
    {
        protected function configureUser(User $user, array $data): void
        {
            parent::configureUser($user, $data);
            $user->setCustomField($data['customField'] ?? null);
        }
    }
    
  2. Pre/Post Save Logic (Unchanged) Use Doctrine lifecycle callbacks:

    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * @ORM\PrePersist
     */
    public function setCreatedAt()
    {
        $this->createdAt = new \DateTime();
    }
    
  3. API Resource Transformers (Unchanged) Create a custom serializer for API responses.

  4. Bulk Operations (Updated) Combine UserGenerator with bulk updates:

    // Generate and save in bulk
    $users = $userGenerator->generateBulk(100, ['emailTemplate' => 'user{index}@example.com']);
    $entityManager->persist($users); // Doctrine bulk persist
    $entityManager->flush();
    

Configuration Quirks

  1. Security.yaml Overrides (Unchanged) Ensure the user_provider points to your custom provider.

  2. Environment-Specific Roles (Unchanged) Use Laravel’s config() to dynamically assign roles.

  3. Caching User Lookups (Updated) Cache UserRepository queries, but invalidate after bulk operations:

    // After bulk generation
    Cache::forget
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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