Creating Microservices with Symfony- Step By Step
Mayur Koshti
Follow
4 min read
Sep 22, 2024
55
Creating Microservices with Symfony
Microservices architecture has gained popularity due to its ability to break down a
monolithic application into smaller, manageable services.
In this guide, I’ll show you how to create microservices using Symfony, a popular PHP
framework.
Contents
1. What is Microservices Architecture?
2. Why Symfony for Microservices?
3. Setting Up a Symfony Microservice
∘ Prerequisites:
∘ Step 1: Install Symfony
∘ Step 2: Install Required Dependencies
4. Building a Simple Microservice Example
∘ Step 1: Creating the Service Entity
∘ Step 2: Create a Controller for User API
∘ Step 3: Configure Routes
∘ Step 4: Test the Microservice
5. Communication Between Microservices
∘ 1. HTTP Communication:
∘ 2. Message Queues:
∘ 3. API Gateway:
6. Conclusion
1. What is Microservices Architecture?
Microservices architecture divides an application into smaller, loosely coupled services
that communicate over a network.
Each service is independent and focused on a specific functionality. Key characteristics
include:
• Decentralization: Each service manages its own database and logic.
• Scalability: Individual services can be scaled independently.
• Resilience: If one service fails, the others continue functioning.
2. Why Symfony for Microservices?
Symfony is a powerful PHP framework that works well with microservices for several
reasons:
• Built-in Flexibility: Symfony can be configured to create lightweight services.
• API-First Approach: With tools like API Platform, Symfony makes building REST APIs
easier.
• Modular Design: Symfony’s component-based structure fits the microservices
philosophy.
• Interoperability: Works well with Docker, Kubernetes, RabbitMQ, and other
microservice-friendly tools.
3. Setting Up a Symfony Microservice
Let’s create a simple Symfony project and convert it into a microservice.
Prerequisites:
• PHP 8.1+
• Composer
• Symfony CLI
• Docker (optional, but recommended for containerization)
Symfony Docker Integration: A Step-by-Step Guide
How to set up a Symfony application with Docker, including building and running
containers for PHP, Nginx, and MySQL.
medium.com
Step 1: Install Symfony
If you haven’t installed Symfony CLI yet, do so with:
curl -sS https://get.symfony.com/cli/installer | bash
Next, create a new Symfony project:
symfony new user-service --webapp
cd user-service
Step 2: Install Required Dependencies
To build a microservice, we’ll need a few additional packages:
composer require symfony/maker-bundle symfony/serializer-pack symfony/validator-pack
symfony/http-client
How to Create API in PHP: A Comprehensive Guide
If you are looking How to Create API in PHP?. You are on perfect article in which you will
get clear knowledge about…
mycodebook.online
4. Building a Simple Microservice Example
Let’s say we are building a User Management microservice that provides a REST API for
managing users. This service will handle:
• Creating users
• Fetching user data
Step 1: Creating the Service Entity
First, create a User entity.
php bin/console make:entity User
Add fields for id, name, and email in the User.php entity class.
// src/Entity/User.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Entity]
class User
{
#[ORM\Id, ORM\GeneratedValue, ORM\Column(type: 'integer')]
private int $id;
#[ORM\Column(length: 100)]
#[Assert\NotBlank]
private string $name;
#[ORM\Column(length: 100, unique: true)]
#[Assert\Email]
private string $email;
// Getters and setters omitted for brevity
}
Step 2: Create a Controller for User API
Next, create a controller to expose API routes for managing users:
php bin/console make:controller UserController
In the UserController.php file, we’ll define the following routes:
• POST /users: Create a new user
• GET /users/{id}: Get user details by ID
// src/Controller/UserController.php
namespace App\Controller;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
class UserController
{
private $entityManager;
private $serializer;
public function __construct(EntityManagerInterface $entityManager, SerializerInterface
$serializer)
{
$this->entityManager = $entityManager;
$this->serializer = $serializer;
}
#[Route('/users', methods: ['POST'])]
public function createUser(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
$user = new User();
$user->setName($data['name']);
$user->setEmail($data['email']);
$this->entityManager->persist($user);
$this->entityManager->flush();
return new JsonResponse(['status' => 'User created!'], 201);
}
#[Route('/users/{id}', methods: ['GET'])]
public function getUser(int $id): JsonResponse
{
$user = $this->entityManager->getRepository(User::class)->find($id);
if (!$user) {
return new JsonResponse(['error' => 'User not found'], 404);
}
$data = $this->serializer->serialize($user, 'json');
return new JsonResponse(json_decode($data), 200);
}
}
Step 3: Configure Routes
Ensure that your routes are properly configured in config/routes.yaml:
user_service:
resource: '../src/Controller/'
type: annotation
Step 4: Test the Microservice
You can now run your Symfony microservice locally:
symfony server:start
Test the API endpoints using Postman or curl.
Create a user:
curl -X POST http://localhost:8000/users \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "john.doe@example.com"}'
Get user details:
curl http://localhost:8000/users/1
5. Communication Between Microservices
In a real-world application, you’ll likely need multiple microservices that interact with each
other.
There are several ways to achieve this in Symfony:
1. HTTP Communication:
• You can use Symfony’s HttpClient to send requests between services.
$client = HttpClient::create();
$response = $client->request('GET', 'http://other-service/api/endpoint');
2. Message Queues:
• Use RabbitMQ or Apache Kafka to send asynchronous messages between services.
composer require enqueue/amqp-bunny
After configuring RabbitMQ, you can send messages between services without needing
direct HTTP communication.
3. API Gateway:
• Use API gateways like Kong or Traefik to route requests to the correct
microservices.
Symfony API Platform Example: Building a Simple REST API
The Symfony API Platform is an open-source framework that allows developers to quickly
create fully-featured APIs.
medium.com
6. Conclusion
Symfony provides a robust foundation for building microservices. By leveraging its
components and third-party integrations, you can create scalable, maintainable, and
efficient microservice-based systems.
With Symfony’s flexibility, it’s easy to build both REST APIs and inter-service
communication mechanisms.
This basic user management microservice can serve as a starting point for a more complex
microservices architecture.
You can expand it by adding features like authentication, database integration, and service
discovery using tools like Kubernetes.