@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
|
composer require --dev doctrine/doctrine-fixtures-bundle
|
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 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
|
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
@lew
To run fixtures in Symfony, follow these steps:
1
|
composer require --dev doctrine/doctrine-fixtures-bundle |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
use DoctrineBundleFixturesBundleFixture; use DoctrinePersistenceObjectManager; use AppBundleEntityUser; class LoadUserData extends Fixture { public function load(ObjectManager $manager) { $user = new User(); $user->setUsername('admin'); $user->setPassword('password'); $manager->persist($user); $manager->flush(); } } |
1 2 3 4 |
services: # ... AppDataFixturesORMLoadUserData: tags: ['doctrine.fixture.orm'] |
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 fixtures to the existing data, you can use the --append
option:
1
|
php bin/console doctrine:fixtures:load --append |
That's it! Your fixtures will be executed, and the data will be loaded into the database.