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

atoomstudio/user-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require atoomstudio/user-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        AtoomStudio\UserBundle\AtoomStudioUserBundle::class => ['all' => true],
    ];
    
  2. Database Migration Run the provided migration (located in vendor/atoomstudio/user-bundle/migrations/) or manually create the fos_user and sonata_user tables:

    php bin/console doctrine:migrations:execute --query="CREATE TABLE fos_user..."
    
  3. First Use Case: Basic User Registration Enable the registration controller in config/routes.yaml:

    sonata_user_register:
        resource: "@AtoomStudioUserBundle/Resources/config/routing/registration.xml"
        prefix: /register
    

    Test registration at /register.


Where to Look First

  • Configuration: config/packages/atoomstudio_user.yaml (auto-generated; override as needed).
  • Templates: vendor/atoomstudio/user-bundle/Resources/views/ (extend via Symfony’s template inheritance).
  • Admin Panel: Access via /admin (if SonataAdminBundle is configured).
  • Google Authenticator: Enabled via sonata_user.google_authenticator config (see below).

Implementation Patterns

1. User Management Workflows

CRUD via SonataAdmin

Leverage SonataAdmin for user management:

// src/Admin/UserAdmin.php
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;

class UserAdmin extends AbstractAdmin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('username')
            ->add('email')
            ->add('plainPassword', 'repeated', ['type' => 'password']);
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper->add('username');
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->add('username')
            ->add('email')
            ->add('enabled', 'boolean');
    }
}

Register the admin in config/packages/sonata_admin.yaml:

sonata_admin:
    options:
        models:
            AtoomStudio\UserBundle\Entity\User: ~

Custom User Fields

Extend the User entity (located at vendor/atoomstudio/user-bundle/Entity/User.php):

// src/Entity/UserExtension.php
use Doctrine\ORM\Mapping as ORM;
use AtoomStudio\UserBundle\Entity\User as BaseUser;

class User extends BaseUser
{
    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $customField;

    // Getters/setters...
}

Update the migration and rebuild the form in UserAdmin.


2. Authentication & Security

Form Login

Configure in config/packages/security.yaml:

security:
    firewalls:
        main:
            form_login:
                login_path: sonata_user_security_login
                check_path: sonata_user_security_check

Google Authenticator

Enable in config/packages/atoomstudio_user.yaml:

sonata_user:
    google_authenticator:
        enabled: true
        secret_length: 32

Trigger 2FA setup in a controller:

use Sonata\UserBundle\Model\UserInterface;
use Sonata\UserBundle\GoogleAuthenticator\GoogleAuthenticator;

public function enable2FA(UserInterface $user)
{
    $authenticator = $this->container->get('sonata.user.google_authenticator');
    $secret = $authenticator->generateSecret();
    $user->setGoogleAuthenticatorSecret($secret);
    $user->setGoogleAuthenticatorEnabled(true);
    $entityManager->persist($user);
    $entityManager->flush();

    return $authenticator->getQRContent($user->getEmail(), $secret);
}

3. API Integration (Optional)

Use FOSRestBundle (dev dependency) to expose user endpoints:

# config/routes/api.yaml
sonata_user_api:
    resource: "@AtoomStudioUserBundle/Resources/config/routing/api.xml"
    prefix: /api

Example endpoint: /api/users (GET/POST/PUT/DELETE).


Gotchas and Tips

1. PHP Version Quirks

  • PHP 5.6/7.0 Compatibility: Avoid modern PHP features (e.g., typed properties, arrow functions).
  • Deprecated Methods: Some SonataUserBundle methods may be renamed or removed. Check the original SonataUserBundle docs for updates.

2. Configuration Pitfalls

  • Missing Dependencies: Ensure sonata-project/admin-bundle and friendsofsymfony/user-bundle are installed.
  • Route Conflicts: SonataUserBundle registers routes under /register, /login, etc. Avoid naming conflicts in your app.
  • Database Schema: The bundle expects specific table names (fos_user, sonata_user). Customize via Doctrine extensions if needed.

Debugging Tip:

php bin/console debug:container sonata.user

Lists all available services (e.g., sonata.user.manager, sonata.user.google_authenticator).


3. Common Debugging Scenarios

Issue: Registration Fails Silently

  • Cause: Validation errors or missing CSRF token.
  • Fix: Check var/log/dev.log and enable debug mode:
    # config/packages/dev/atoomstudio_user.yaml
    sonata_user:
        debug: true
    

Issue: Google Authenticator Not Working

  • Cause: Secret not saved or 2FA not enabled in the user entity.
  • Fix: Verify google_authenticator_secret and google_authenticator_enabled fields exist in the User entity.

Issue: Admin Panel Not Showing Users

  • Cause: Missing UserAdmin registration or ACL permissions.
  • Fix:
    php bin/console sonata:admin:generate
    
    Then register the admin as shown in Implementation Patterns.

4. Extension Points

Custom User Provider

Override the default fos_user.user_provider:

# config/packages/security.yaml
security:
    providers:
        my_user_provider:
            id: my.custom.user_provider

Example Provider:

// src/Security/MyUserProvider.php
use Sonata\UserBundle\SonataUserProvider;

class MyUserProvider extends SonataUserProvider
{
    public function loadUserByUsername($username)
    {
        // Custom logic...
    }
}

Event Listeners

Listen to user events (e.g., sonata.user.register):

// src/EventListener/UserListener.php
use Sonata\UserBundle\Event\UserEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class UserListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            UserEvent::REGISTER => 'onUserRegister',
        ];
    }

    public function onUserRegister(UserEvent $event)
    {
        $user = $event->getUser();
        // Send welcome email, etc.
    }
}

5. Performance Tips

  • Cache User Data: Use Symfony’s cache system for frequent user lookups:
    $user = $this->container->get('sonata.user.manager')->findUserBy(['username' => 'john']);
    $this->container->get('cache')->set('user:john', $user, 3600);
    
  • Batch Processing: Use Doctrine’s BATCH_SIZE for large user exports:
    # config/packages/doctrine.yaml
    doctrine:
        orm:
            dql:
                string_functions:
                    GROUP_CONCAT: AtoomStudio\UserBundle\Doctrine\GroupConcat
    
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