@orpha
To load fixtures in Symfony, you can 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 AppEntityUser; use DoctrineBundleFixturesBundleFixture; use DoctrinePersistenceObjectManager; class UserFixtures extends Fixture { public function load(ObjectManager $manager) { $user = new User(); $user->setUsername('john'); $user->setPassword('password'); $manager->persist($user); $manager->flush(); } } |
1
|
php bin/console doctrine:fixtures:load |
This command will load all the fixtures in the src/DataFixtures
directory. You can also specify a specific fixture class or group using the --fixtures
and --group
options.
That's it! Your fixtures should now be loaded into the database.
@orpha
Please note that the code provided above is for Symfony 3.4 and earlier versions. Symfony 4 introduced a new way to load fixtures using the DoctrineFixtureTrait. Here's how to load fixtures in Symfony 4 and later versions:
1
|
composer require --dev doctrine/doctrine-fixtures-bundle |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
use AppEntityUser; use DoctrineBundleFixturesBundleFixture; use DoctrinePersistenceObjectManager; use DoctrineCommonDataFixturesDependentFixtureInterface; class UserFixtures extends Fixture implements DependentFixtureInterface { use DoctrineBundleFixturesBundleCommandLoadDataFixturesDoctrineCommandTrait; public function load(ObjectManager $manager) { // Create and persist entities // Use $manager->persist($entity) to persist entities $manager->flush(); } public function getDependencies() { return [ OtherFixtureClass::class, AnotherFixtureClass::class, // Add additional fixtures on which this fixture depends ]; } } |
1
|
php bin/console doctrine:fixtures:load |
This command will load all the fixtures in the src/DataFixtures directory. You can also specify a specific fixture class or group using the --fixtures
and --group
options.
That's it! Your fixtures should now be loaded into the database.