Symfony & Doctrine CRUD Operations: Tutorial & Examples

Updated: January 14, 2024 By: Guest Contributor Post a comment

Introduction

Developing web applications efficiently requires a robust framework coupled with an efficient ORM (Object-Relational Mapping) tool. Symfony, a prominent PHP framework, and Doctrine, a powerful ORM, together offer this combination. In this tutorial, we’ll dive into the nitty-gritty of implementing CRUD operations—Create, Read, Update, and Delete—using Symfony and Doctrine.

CRUD Operations Overview

CRUD operations are the four basic functions necessary to manage data in any application. Here’s what each of them stand for:

  • Create: The process of adding new data into your database.
  • Read: The act of querying your database to retrieve data.
  • Update: The operation to modify existing data within your database.
  • Delete: The operation to remove data from your database.

Setting Up Symfony & Doctrine

Before delving into code, ensure you have Symfony installed. If not, you can follow the Symfony installation guide in this tutorial: How to set up and configure Symfony. With Symfony ready, let’s set up a new project:

symfony new my_project --full

To begin working with Doctrine, open your project directory:

cd my_project

Creating an Entity

An ‘entity’ in Doctrine represents a table in a database. Let’s say we want to create a Product entity:

php bin/console make:entity Product

The console will then prompt you to enter the fields for the Product entity. Once done, you can create the corresponding table in your database:

php bin/console doctrine:migrations:migrate

This command creates the SQL queries necessary and updates your database.

Create Operation

To add data to our database, we will create a new Product object and persist it using Doctrine’s EntityManager:


// src/Controller/ProductController.php

use App\Entity\Product;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;

public function createProduct(EntityManagerInterface $entityManager): Response
{
    $product = new Product();
    $product->setName('Keyboard')->setPrice(1999);

    $entityManager->persist($product);
    $entityManager->flush();

    return new Response('Saved new product with id '.$product->getId());
}

Read Operation

Reading data again involves the use of the EntityManager (or a repository) to retrieve a particular record or a set of records:


// src/Controller/ProductController.php

use App\Repository\ProductRepository;

public function showProduct(ProductRepository $productRepository, int $productId): Response
{
    $product = $productRepository->find($productId);

    if (!$product) {
        throw $this->createNotFoundException('No product found for id '.$productId);
    }

    // ... (do something, like return a view)
}

Update Operation

To update a record, retrieve the item using the repository and then make and persist changes:


// src/Controller/ProductController.php

public function updateProduct(EntityManagerInterface $entityManager, int $productId): Response
{
    $product = $entityManager->getRepository(Product::class)->find($productId);

    if (!$product) {
        throw $this->createNotFoundException('No product found for id '.$productId);
    }

    $product->setName('New Keyboard Name');
    $entityManager->flush();

    return new Response('Product updated!');
}

Delete Operation

Deleting a record is as straightforward as retrieving the entity and removing it with the help of the EntityManager:


// src/Controller/ProductController.php

public function deleteProduct(EntityManagerInterface $entityManager, int $productId): Response
{
    $product = $entityManager->getRepository(Product::class)->find($productId);

    if ($product) {
        $entityManager->remove($product);
        $entityManager->flush();
    }

    return new Response('Product deleted if it existed.');
}

Conclusion

This tutorial scratched the surface of what Symfony and Doctrine can do together. We’ve learned to perform the basic CRUD operations essential for any application. For further insights and advanced features, you can consult Symfony’s official documentation.

Remember, efficiency comes with practice, and continuously refactoring your code as you learn more about Symfony’s features and Doctrine’s capabilities will ensure your project’s flexibility and robustness.