Lesson 2
Implementing Database Services in Symfony
Implementing Database Services in Symfony

Welcome back to our deep dive into enhancing enterprise capabilities in your Symfony application. In this lesson, we'll shift our focus from session-based data handling to leveraging a database for managing Todo items through Symfony Services and Doctrine ORM.

If you remember from our previous session, Doctrine ORM allows us to manage our database interactions using PHP objects, making our code cleaner and more intuitive. Today, our goal is to transition your existing service class to handle CRUD (Create, Read, Update, Delete) operations on the Todo entity through the database.

Symfony's service classes are designed to encapsulate business logic, helping you maintain a cleaner architecture. By the end of this lesson, you'll be proficient in updating and utilizing a TodoService class that interacts with your database efficiently.

Setting Up the TodoService

First, we need to configure the TodoService class to handle database operations. This class will manage all CRUD operations for the Todo entity. We'll inject two key dependencies: the EntityManagerInterface and the TodoRepository. The EntityManagerInterface manages database operations for entities, acting as the central manager for them.

php
1<?php 2 3namespace App\Service; 4 5use App\Entity\Todo; 6use App\Repository\TodoRepository; 7use Doctrine\ORM\EntityManagerInterface; 8 9class TodoService 10{ 11 private $entityManager; 12 private $todoRepository; 13 14 public function __construct(EntityManagerInterface $entityManager, TodoRepository $todoRepository) 15 { 16 $this->entityManager = $entityManager; 17 $this->todoRepository = $todoRepository; 18 } 19}

Here, by setting up these dependencies, we prepare our service class to interact with the database through Doctrine ORM, ensuring that we can easily manage Todo entities.

Next, let's look at implementing the CRUD operations in the TodoService class. These operations will allow us to create, read, update, and delete Todo items in the database.

Retrieving Todo Items

We'll use the TodoRepository to fetch Todo items from the database.

php
1public function getAllTodos(): array 2{ 3 return $this->todoRepository->findAll(); 4} 5 6public function getTodoById(int $id): ?Todo 7{ 8 return $this->todoRepository->find($id); 9}

By utilizing these methods, we can easily retrieve a list of all Todo items, or fetch a specific Todo by its ID, making our data retrieval process straightforward and efficient.

Creating a Todo Item

To add a new Todo item to the database, we use the EntityManagerInterface.

php
1public function addTodoItem(string $title, ?string $description): Todo 2{ 3 $todo = new Todo(); 4 $todo->setTitle($title); 5 $todo->setDescription($description); 6 7 $this->entityManager->persist($todo); 8 $this->entityManager->flush(); 9 10 return $todo; 11}

This method allows us to create a new Todo item, setting its basic properties, persisting it to be managed by Doctrine, and then saving it into the database in one seamless operation. The persist function marks the Todo entity for being managed by Doctrine, and flush commits the changes to the database, saving the new item.

Updating a Todo Item

To modify an existing Todo item, we use the TodoRepository and EntityManagerInterface.

php
1public function modifyTodoItem(int $id, string $title, ?string $description): ?Todo 2{ 3 $todo = $this->getTodoById($id); 4 if ($todo) { 5 $todo->setTitle($title); 6 $todo->setDescription($description); 7 $this->entityManager->flush(); 8 return $todo; 9 } 10 11 return null; 12}

Here, we efficiently update an existing Todo item by finding it through its ID, changing its details if it exists, and then committing these changes to the database.

Deleting a Todo Item

Finally, to remove an existing Todo item, modify the method to use the TodoRepository and EntityManagerInterface.

php
1public function removeTodoItem(int $id): void 2{ 3 $todo = $this->getTodoById($id); 4 if ($todo) { 5 $this->entityManager->remove($todo); 6 $this->entityManager->flush(); 7 } 8}

This method facilitates the deletion of a Todo item by locating it and then using Doctrine's integrated mechanisms to remove it from the database.

The Complete TodoService Class

Let's review the complete TodoService class with all the integrated functions.

php
1<?php 2 3namespace App\Service; 4 5use App\Entity\Todo; 6use App\Repository\TodoRepository; 7use Doctrine\ORM\EntityManagerInterface; 8 9class TodoService 10{ 11 private $entityManager; 12 private $todoRepository; 13 14 public function __construct(EntityManagerInterface $entityManager, TodoRepository $todoRepository) 15 { 16 $this->entityManager = $entityManager; 17 $this->todoRepository = $todoRepository; 18 } 19 20 public function getAllTodos(): array 21 { 22 return $this->todoRepository->findAll(); 23 } 24 25 public function getTodoById(int $id): ?Todo 26 { 27 return $this->todoRepository->find($id); 28 } 29 30 public function addTodoItem(string $title, ?string $description): Todo 31 { 32 $todo = new Todo(); 33 $todo->setTitle($title); 34 $todo->setDescription($description); 35 36 $this->entityManager->persist($todo); 37 $this->entityManager->flush(); 38 39 return $todo; 40 } 41 42 public function modifyTodoItem(int $id, string $title, ?string $description): ?Todo 43 { 44 $todo = $this->getTodoById($id); 45 if ($todo) { 46 $todo->setTitle($title); 47 $todo->setDescription($description); 48 $this->entityManager->flush(); 49 return $todo; 50 } 51 52 return null; 53 } 54 55 public function removeTodoItem(int $id): void 56 { 57 $todo = $this->getTodoById($id); 58 if ($todo) { 59 $this->entityManager->remove($todo); 60 $this->entityManager->flush(); 61 } 62 } 63}
Recap and Moving Forward

In this lesson, we've transitioned our TodoService class to effectively handle CRUD operations on the Todo entity using the database:

  1. Configured the service class with necessary dependencies.
  2. Implemented retrieval functions to get Todo items.
  3. Added creation, update, and deletion functionalities.
  4. Provided a complete code example with all the integrated methods.

Your next step is to engage with the practice exercises where you'll apply what you've learned to solidify your understanding. Dive in and become proficient at managing database operations within your Symfony application.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.