Symfony Doctrine Cheatsheet

Installing

  1. cd into your project directory and run composer require doctrine
  2. Open the .env file and set your local config.
DATABASE_URL=mysql://root:password@127.0.0.1:3306/the_spacebar

This uses root user and password password and sets the name of the database to the_spacebar

Create Database

In the console run ./bin/console doctrine:database:create

Create Doctrine Entity

If you don’t already have the maker bundle installed, run:

composer require symfony/maker-bundle —dev

Docs located here: The Symfony MakerBundle (Symfony Bundles Docs)

To create an entity, run

./bin/console make:entity

Follow the instructions at the prompt. When you’re all done, it will have created an entity class in the Entity directory and an entity repository in the Repository directory

Annotations

Docs here: Annotations Reference – Object Relational Mapper (ORM) – Doctrine

Migrations

To create a table for the entity, first create a migration using the maker bundle tool

./bin/console make:migration

To run the migration:

./bin/console doctrine:migrations:migrate

To see the status of the migrations:

./bin/console doctrine:migrations:status

Save to Database

  1. Instantiate and populate a model in your controller. For example, in ArticleAdminController.php:
/**
 * @Route("/admin/article/new")
 * @return Response
 */
public function new(EntityManagerInterface $em)
{
    $article = new Article();
    $article->setTitle('Why Asteroids Taste Like Bacon')
        ->setSlug('why-asteroids-taste-like-bacon-'.rand(100, 999))
        ->setContent(
            <<<EOF
Spicy **jalapeno bacon** ipsum dolor amet veniam shank in dolore. Ham hock nisi landjaeger cow,
lorem proident [beef ribs](https://baconipsum.com/) aute enim veniam ut cillum pork chuck picanha. Dolore reprehenderit
labore minim pork belly spare ribs cupim short loin in. Elit exercitation eiusmod dolore cow
**turkey** shank eu pork belly meatball non cupim.
EOF
        );

      // Doctrice part
    $em->persist($article); // Create it - you could call this multiple times and just call flush() at the end
      $em->flush(); // Write to db

    return new Response('space rocks... include comets, asteroids & meteoroids');
}

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.