Installation:
composer require friendsofsymfony/user-bundle
Add to config/bundles.php:
return [
// ...
FriendsOfSymfony\UserBundle\FOSUserBundle::class => ['all' => true],
];
Database Configuration:
Update config/packages/doctrine.yaml to include the User entity:
orm:
mappings:
FOSUserBundle: ../../vendor/friendsofsymfony/user-bundle/Resources/config/doctrine
First Use Case:
Run migrations to create the user table:
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate
Routing:
Enable FOSUserBundle routes in config/routes.yaml:
fos_user:
resource: "@FOSUserBundle/Resources/config/routing/all.xml"
prefix: /user
Form Integration: Extend the default registration form:
// src/Form/RegistrationFormType.php
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseRegistrationFormType;
class RegistrationFormType extends BaseRegistrationFormType {
public function buildForm(FormBuilderInterface $builder, array $options) {
parent::buildForm($builder, $options);
$builder->add('custom_field', TextType::class);
}
}
Controller Override: Override the registration controller to customize logic:
// src/Controller/RegistrationController.php
use FOS\UserBundle\Controller\RegistrationController as BaseRegistrationController;
class RegistrationController extends BaseRegistrationController {
public function registerAction() {
// Custom logic (e.g., validation, email templates)
return parent::registerAction();
}
}
Email Templates:
Override default templates in templates/FOSUserBundle/Registration/reset.html.twig.
Token Lifecycle:
Use the fos_user.user_manager service to manage tokens:
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(['email' => 'user@example.com']);
$token = $userManager->createResetToken($user);
Security Configuration:
Configure security.yaml to use FOSUserBundle’s provider:
security:
providers:
fos_userbundle:
id: fos_user.user_provider.username_email
firewalls:
main:
form_login:
provider: fos_userbundle
Custom User Provider: Extend the default provider for custom logic:
// src/Security/UserProvider.php
use FOS\UserBundle\Model\UserManagerInterface;
class CustomUserProvider implements UserProviderInterface {
private $userManager;
public function __construct(UserManagerInterface $userManager) {
$this->userManager = $userManager;
}
public function loadUserByUsername($username) {
return $this->userManager->findUserBy(['username' => $username]);
}
}
Event Listeners:
Subscribe to FOSUserBundle events (e.g., fos_user.registered) for post-actions:
// src/EventListener/UserListener.php
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class UserListener implements EventSubscriberInterface {
public static function getSubscribedEvents() {
return [
FOSUserEvents::REGISTERED => 'onUserRegistered',
];
}
public function onUserRegistered(GetResponseUserEvent $event) {
// Send welcome email, log activity, etc.
}
}
Custom User Class:
Extend the default User entity:
// src/Entity/User.php
use FOS\UserBundle\Model\User as BaseUser;
class User extends BaseUser {
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $customField;
// Getters/setters
}
API Integration: Use FOSUserBundle with API Platform or Symfony Serializer:
# config/packages/api_platform.yaml
resources:
App\Entity\User:
collectionOperations:
get:
security: "is_granted('ROLE_ADMIN')"
Route Conflicts:
FOSUserBundle routes may conflict with existing routes. Use prefix in routing.yaml or override controllers to avoid clashes.
Doctrine Migrations:
Always run doctrine:migrations:diff after extending the User entity to update the schema.
Security Context:
FOSUserBundle does not handle authentication—pair it with Symfony’s SecurityBundle for full auth functionality.
Token Expiry:
Reset tokens expire by default (configurable in config/packages/fos_user.yaml). Ensure your reset route respects this:
fos_user:
reset:
token_ttl: 86400 # 1 day in seconds
Event Debugging: Enable Symfony’s event dispatcher debug mode:
php bin/console debug:event-dispatcher
Form Errors: Validate custom fields in the registration form:
$builder->add('custom_field', TextType::class, [
'constraints' => [new NotBlank(), new Length(['max' => 100])],
]);
User Loading:
If users aren’t loading, verify your UserProvider and UserManager services are properly configured in services.yaml:
services:
App\Security\UserProvider:
arguments:
- '@fos_user.user_manager'
Custom Validation:
Add constraints to the User entity:
use Symfony\Component\Validator\Constraints as Assert;
/**
* @Assert\Unique(entityManager="doctrine.orm.entity_manager", message="Email already taken")
*/
private $email;
Profile Management: Extend the profile controller to add fields:
// src/Controller/ProfileController.php
use FOS\UserBundle\Controller\ProfileController as BaseProfileController;
class ProfileController extends BaseProfileController {
public function editAction() {
$form = $this->container->get('fos_user.user_manager')->createEditForm($this->getUser());
$form->add('custom_field', TextType::class);
// ...
}
}
MongoDB/CouchDB:
For ODM support, configure fos_user in config/packages/fos_user.yaml:
fos_user:
db_driver: orm # or 'mongodb', 'couchdb'
Translation:
Override translations in translations/messages.en.yaml:
'Registration completed': 'Welcome aboard! Your account is now active.'
Testing:
Use the FOS\UserBundle\Tests\Functional\WebTestCase base class for functional tests:
use FOS\UserBundle\Tests\Functional\WebTestCase;
class UserRegistrationTest extends WebTestCase {
public function testRegistration() {
$client = static::createClient();
// ...
}
}
How can I help you explore Laravel packages today?