How to run fixtures in Symfony?

Member

by lew , in category: PHP Frameworks , 9 months ago

How to run fixtures in Symfony?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 3 months ago

@lew 

In Symfony, fixtures are used to load a predefined set of data into the database. This is useful for testing and for setting up a consistent initial state for your application.


To use fixtures in Symfony, you will need to do the following:

  1. Install the DoctrineFixturesBundle:
1
composer require --dev doctrine/doctrine-fixtures-bundle


  1. Create your fixtures classes. Fixture classes should implement the FixtureInterface interface and define the load method, which is responsible for loading the data into the database.


Here is an example fixture class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
use DoctrineBundleFixturesBundleFixture;
use DoctrineCommonPersistenceObjectManager;

class LoadUserData extends Fixture
{
    public function load(ObjectManager $manager)
    {
        $user = new User();
        $user->setUsername('admin');
        $user->setPassword('password');

        $manager->persist($user);
        $manager->flush();
    }
}


  1. Register your fixtures in the app/config/config_test.yml configuration file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# app/config/config_test.yml

imports:
    - { resource: parameters_test.yml }
    - { resource: security_test.yml }
    - { resource: services_test.yml }

doctrine:
    orm:
        fixtures:
            - AppBundleDataFixturesORMLoadUserData


  1. Load the fixtures using the doctrine:fixtures:load command:
1
php bin/console doctrine:fixtures:load


By default, this command will truncate the database tables before loading the fixtures. If you want to append the fixtures to the existing data, you can use the --append option:

1
php bin/console doctrine:fixtures:load --append


You can also specify a specific set of fixtures to load using the --fixtures option:

1
php bin/console doctrine:fixtures:load --fixtures=path/to/fixtures1 --fixtures=path/to/fixtures2


For more information on using fixtures in Symfony, you can refer to the DoctrineFixturesBundle documentation:


https://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html