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

c975l/user-files-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Run composer require c975l/user-files-bundle (though note the bundle is read-only; consider migrating to c975L/UserBundle). Ensure FOSUserBundle is installed (composer require friendsofsymfony/user-bundle).

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

    return [
        // ...
        c975L\UserFilesBundle\c975LUserFilesBundle::class => ['all' => true],
        FOS\UserBundle\FOSUserBundle::class => ['all' => true],
    ];
    
  3. Database Configuration Update config/packages/doctrine.yaml to include the bundle’s entity mappings (check src/Resources/config/doctrine/ for User.orm.xml).

  4. First Use Case Run migrations:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    

    Access the registration form at /register (if enabled) or /admin for user management.


Implementation Patterns

Core Workflows

  1. User Registration with Challenges

    • Extend RegistrationFormType (located in src/Resources/config/validation.yml or src/Form/) to add custom validation (e.g., CAPTCHA or terms acceptance).
    • Override the registration template (src/Resources/views/Registration/register.html.twig) to include the challenge field.
    • Example challenge logic in a custom validator:
      // src/Validator/Constraints/ChallengeValidator.php
      use Symfony\Component\Validator\Constraint, Symfony\Component\Validator\ConstraintValidator;
      
      class ChallengeValidator extends ConstraintValidator {
          public function validate($value, Constraint $constraint) {
              if ($value !== 'expected_answer') {
                  $this->context->buildViolation($constraint->message)
                      ->addViolation();
              }
          }
      }
      
  2. Avatar Uploads

    • Use the User entity’s avatar field (type string for path, file for uploads).
    • Configure file uploads in config/packages/vich_uploader.yaml (if using VichUploaderBundle):
      vich_uploader:
          db_driver: orm
          mappings:
              user_avatar:
                  uri_prefix: /uploads/avatars
                  upload_destination: '%kernel.project_dir%/public/uploads/avatars'
      
    • Bind the upload in a form type:
      // src/Form/UserType.php
      use Vich\UploaderBundle\Form\Type\VichFileType;
      
      $builder->add('avatar', VichFileType::class, [
          'required' => false,
          'allow_delete' => true,
      ]);
      
  3. Disabling Registration

    • Set registration.enabled: false in config/packages/fos_user.yaml to restrict registration to admin-only.
    • Use fos_user.user_manager service to programmatically create users:
      $user = $userManager->createUser();
      $user->setUsername('admin');
      $user->setPassword('secure_password');
      $user->setEnabled(true);
      $userManager->updateUser($user);
      
  4. Admin Panel Integration

    • Extend the FOSUserBundle admin controller (src/Controller/Admin/UserController.php) to customize user listings or actions.
    • Example: Add a custom action to bulk-export user data:
      // src/Controller/Admin/UserController.php
      use Symfony\Component\HttpFoundation\Response;
      use Symfony\Component\Routing\Annotation\Route;
      
      #[Route('/admin/users/export', name: 'user_export')]
      public function exportUsers(UserManager $userManager): Response {
          $users = $userManager->findAll();
          // Generate CSV/Excel response...
      }
      

Gotchas and Tips

Pitfalls

  1. Deprecation Warning

    • The bundle is read-only and replaced by c975L/UserBundle. Plan a migration to avoid future compatibility issues.
    • Key changes in the successor:
      • Unified user and file management.
      • Improved Symfony 5+ compatibility.
  2. Missing Documentation

    • The README lacks details on:
      • Customizing the "challenge" field (e.g., dynamic questions).
      • Overriding templates (check src/Resources/views/ for base templates).
    • Workaround: Inspect src/Controller/ and src/Form/ for entry points.
  3. File Upload Quirks

    • The avatar field assumes a specific directory structure (/uploads/avatars). Ensure:
      • The directory exists (mkdir -p public/uploads/avatars).
      • Permissions are set (chmod -R 775 public/uploads).
    • If using VichUploaderBundle, clear the cache after configuration changes:
      php bin/console cache:clear
      
  4. Registration Flow Issues

    • If registration fails silently, check:
      • fos_user.registration.form.type in fos_user.yaml (ensure it points to a valid form class).
      • Validation errors in src/Validator/Constraints/ or src/Resources/config/validation.yml.
    • Debug with:
      php bin/console debug:form fos_user_registration_form
      
  5. Symfony 5+ Compatibility

    • The bundle may not support Symfony Flex autoloading. Manually add:
      # config/autoload.yaml
      imports:
          - { resource: "%kernel.project_dir%/vendor/c975l/user-files-bundle/config/*.yaml" }
      

Debugging Tips

  1. Dump User Entity Use a controller to inspect the User entity structure:

    #[Route('/debug/user', name: 'debug_user')]
    public function debugUser(EntityManagerInterface $em): Response {
        $user = $em->getRepository(User::class)->find(1);
        dump($user); // Check fields like `avatar`, `firstname`, etc.
        return new Response('Done');
    }
    
  2. Template Overrides Copy the base template from vendor/c975l/user-files-bundle/src/Resources/views/ to templates/bundles/c975luserfiles/ to override without modifying the bundle.

  3. Event Listeners Extend user lifecycle events (e.g., UserEvents::REGISTRATION_SUCCESS) in src/EventListener/:

    // src/EventListener/UserRegistrationListener.php
    use FOS\UserBundle\FOSUserEvents;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class UserRegistrationListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess',
            ];
        }
    
        public function onRegistrationSuccess(GetResponseUserEvent $event) {
            // Send welcome email, log event, etc.
        }
    }
    

Extension Points

  1. Custom User Fields Add fields to the User entity (extend c975L\UserFilesBundle\Entity\User):

    // src/Entity/User.php
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity]
    class User extends BaseUser {
        #[ORM\Column(type: 'string', length: 255, nullable: true)]
        private $customField;
    
        // Getters/setters...
    }
    

    Update the form type and validation accordingly.

  2. API Integration Use Symfony’s serializer to expose user data:

    # config/packages/serializer.yaml
    framework:
        serializer:
            mapping:
                paths: ['%kernel.project_dir%/config/serializer']
    

    Create a UserNormalizer or use attributes:

    #[Serializer\SerializedName('full_name')]
    public function getFullName(): string {
        return $this->getFirstname() . ' ' . $this->getLastname();
    }
    
  3. Multi-Tenant Support Add a tenant_id field to the User entity and filter queries in repositories:

    // src/Repository/UserRepository.php
    public function findByTenant(int $tenantId) {
        return $this->createQueryBuilder('u')
            ->where('u.tenantId = :tenantId')
            ->setParameter('tenantId', $tenantId)
            ->getQuery()
            ->getResult();
    }
    
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