Get started with Symfony 6 for beginners — Part 3.1| Database, Doctrine, Entity.
--
This article will demonstrate how to populate a database with fake data (fake blog information). For this Open up a terminal window and run the following command:
$ composer require --dev orm-fixtures
This command will install the extra library and will create a file App\DataFixtures\AppFixtures
Open that file — src/DataFixtures/AppFixtures.php
and let's create a few blog posts.
<?phpnamespace App\DataFixtures;use Doctrine\Bundle\FixturesBundle\Fixture;use Doctrine\Persistence\ObjectManager;use App\Entity\Blog;class AppFixtures extends Fixture{public function load(ObjectManager $manager): void{for ($i = 1; $i < 6; $i++) {$blog = new Blog;$blog->setTitle('Post ' . $i);$blog->setShortDescription('Short descr for post number ' . $i);$blog->setBody("Lorem Ipsum is simply dummy text of theprinting and typesetting industry. Lorem Ipsum has beenthe industry's standard dummy text ever since the 1500s,when an unknown printer took a galley of type and scrambledit to make a type specimen book.");$manager->persist($blog);}$manager->flush();}}
As you can see, we made five blog posts. ObjectManager
is a doctrine persistence layer. It's an object that we use to manipulate our entities.
In the example above we used persist
and flush
methods. Persist tells to ObjectManager
that we can store this entity state in the database.
And flush
flushes all changes to objects and saves them into a database(MySQL in our case).
Run this command to load these new entities into a database:
symfony console doctrine:fixtures:load
Thanks for reading. Comments/corrections/questions are welcomed.