These integration guides are not official documentation and the Strapi Support Team will not provide assistance with them.
What Is Symfony?
Symfony is a powerful PHP framework for building scalable, complex web applications. It follows the Model-View-Controller (MVC) pattern, which separates application logic from presentation, ensuring better maintainability. Symfony’s modular architecture relies on reusable components and bundles that act as plugins, enabling easy customization and extension.
Key features include platform and database engine independence, enterprise-ready architecture, and extensive customization options. Its component-based approach allows developers to use libraries independently, while its templating system supports content localization and internationalization. With robust security features and strong community support, Symfony is perfect for high-performance, scalable web applications.
Why Integrate Symfony with Strapi
Integrating Symfony with Strapi combines the strengths of both platforms, addressing their limitations while creating a powerful and flexible solution.
Key Benefits
Here are the main advantages of using Strapi alongside Symfony:
- Strapi as a Content Command Center: Strapi offers a user-friendly admin interface for content management. This allows non-technical team members to manage content without code involvement, while Symfony developers can focus on complex business logic.
- Customizable Content Types: Easily define and modify content structures without altering the database schema.
- Built-in User Management: Benefit from ready-to-use authentication and authorization features for secure access.
- Flexible Plugin System: Extend functionality with community or custom plugins.
- Comprehensive Media Library: Efficient management of images, videos, and other media assets.
- Internationalization Support: Strapi’s built-in i18n plugin supports multilingual applications.
Why It Works
The integration works well because it leverages the strengths of both platforms in a complementary way:
- API Communication: Symfony can retrieve content from Strapi via REST or GraphQL APIs. It offers flexibility for frontend development teams.
- Specialized Tooling: Symfony manages the application logic while Strapi handles content. It enables each platform to focus on what it does best.
- Improved Developer Experience: Team members use tools tailored to their expertise.
- Scalability & Flexibility: Both systems scale independently, ensuring ease of updates and maintenance.
Integrating Symfony with Strapi results in more maintainable, scalable, and content-rich web applications, which are ideal for projects requiring frequent content updates or multi-channel content delivery.
Keep in touch with the latest Strapi and Symfony updates
How to Integrate Symfony with Strapi: Deployment Guide
Integrating Symfony with Strapi provides enhanced content management for your Symfony application. This guide walks you through three key steps: setting up your development environment, creating a basic Strapi API, and connecting Symfony to the Strapi API.
Sett up the Development Environment
Before diving in, make sure you have these tools installed:
- Node.js (Active LTS version; check your application's requirements)
- A Node.js package manager (npm, yarn, etc.)
- PHP 8.2+ (if working with the latest Symfony)
- Git
- Composer
To set up your development environment:
- Install Symfony:
1composer create-project symfony/website-skeleton my-symfony-project
- Install Strapi:
1npx create-strapi@latest my-strapi-project
- Navigate to your Strapi project and start the server:
1cd my-strapi-project
2npm run develop
- Access the Strapi admin panel at http://localhost:1337/admin and create your first administrator account.
Create a Basic API with Strapi
With your environment ready, let's create a simple API in Strapi:
- In the Strapi admin panel, go to Content-Type Builder.
- Create a new collection type (e.g., "Articles").
- Add fields to your content type (e.g., Title, Content, Author).
- Save your content type and apply changes.
- Go to Settings > Roles & Permissions and set appropriate permissions for your API.
- Create some sample content in the Content Manager.
To generate an API token for secure communication:
- Navigate to Settings > API Tokens.
- Create a new API token with appropriate permissions.
- Save the generated token securely; you'll need it for Symfony integration.
Connect Symfony to Strapi's API
Let's connect your Symfony app to the Strapi API:
- Install the Symfony HTTP Client:
1composer require symfony/http-client
- Create a Strapi client service in your Symfony project:
1// src/Service/StrapiClient.php
2namespace App\Service;
3
4use Symfony\Contracts\HttpClient\HttpClientInterface;
5
6class StrapiClient
7{
8 private $httpClient;
9 private $strapiUrl;
10
11 public function __construct(HttpClientInterface $httpClient, string $strapiUrl)
12 {
13 $this->httpClient = $httpClient;
14 $this->strapiUrl = $strapiUrl;
15 }
16
17 public function getArticles(): array
18 {
19 $response = $this->httpClient->request('GET', "{$this->strapiUrl}/api/articles", [
20 'headers' => [
21 'Authorization' => 'Bearer ' . $_ENV['STRAPI_API_TOKEN'],
22 ],
23 ]);
24
25 return $response->toArray();
26 }
27}
- Configure your Symfony
.env
file:
1STRAPI_API_URL=http://localhost:1337
2STRAPI_API_TOKEN=your_api_token_here
- Create a controller to use the Strapi client:
1// src/Controller/ArticleController.php
2namespace App\Controller;
3
4use App\Service\StrapiClient;
5use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
6use Symfony\Component\HttpFoundation\Response;
7use Symfony\Component\Routing\Annotation\Route;
8
9class ArticleController extends AbstractController
10{
11 #[Route('/articles', name: 'article_list')]
12 public function list(StrapiClient $strapiClient): Response
13 {
14 $articles = $strapiClient->getArticles();
15
16 return $this->render('articles/list.html.twig', [
17 'articles' => $articles['data'],
18 ]);
19 }
20}
- Create a Twig template to display the articles:
1{# templates/articles/list.html.twig #}
2{% extends 'base.html.twig' %}
3
4{% block body %}
5 <h1>Articles</h1>
6 {% for article in articles %}
7 <h2>{{ article.title }}</h2>
8 <p>{{ article.content }}</p>
9 {% endfor %}
10{% endblock %}
To improve performance, you can implement caching:
1use Symfony\Contracts\Cache\CacheInterface;
2use Symfony\Contracts\Cache\ItemInterface;
3
4public function getArticles(): array
5{
6 return $this->cache->get('articles', function (ItemInterface $item) {
7 $item->expiresAfter(3600); // Cache for 1 hour
8
9 $response = $this->httpClient->request('GET', "{$this->strapiUrl}/api/articles", [
10 'headers' => [
11 'Authorization' => 'Bearer ' . $_ENV['STRAPI_API_TOKEN'],
12 ],
13 ]);
14
15 return $response->toArray();
16 });
17}
Following these steps can help you integrate Symfony with Strapi for seamless content management and application logic separation. Depending on your needs, consider using Strapi's REST or GraphQL APIs and optimizing your application with caching and security features. As your application grows, automate tasks with Strapi and consider webhook integration for real-time updates. This approach provides scalability, flexibility, and efficient content delivery.
Keep in touch with the latest Strapi and Symfony updates
Project Example: Integrate Symfony with Strapi
Let's explore a practical example of integrating Symfony with Strapi in an e-commerce platform. This integration leverages Symfony’s strengths in handling complex business logic and Strapi’s robust content management capabilities.
Project Overview: E-commerce Platform
Our e-commerce platform uses Symfony to handle complex business logic, user authentication, and order processing, while Strapi manages product information, categories, and marketing content.
Key Integration Points
Below are some of the core areas where integration typically occurs and how each platform contributes:
- Product Catalog: Strapi manages product details, while Symfony handles inventory and pricing logic.
- Content Management: Marketing pages, blog posts, and promotional banners are managed in Strapi and consumed by Symfony.
- User Reviews: Symfony handles user authentication, while review content is stored and managed in Strapi.
Implementation Details
Bringing Symfony and Strapi together requires thoughtful setup on both sides: content modeling in Strapi and robust API integration in Symfony. This section outlines how we structured content within Strapi and shows example code for fetching and displaying that content through Symfony.
Strapi Content Structure
Proper content modeling in Strapi is crucial for a scalable and maintainable application.
1Product
2 - Name (string)
3 - Description (rich text)
4 - Images (media)
5 - Category (relation)
6 - Specifications (component)
7
8Category
9 - Name (string)
10 - Description (text)
11 - Image (media)
12
13MarketingBanner
14 - Title (string)
15 - Subtitle (string)
16 - Image (media)
17 - LinkURL (string)
While implementing our project, we decided to upgrade, updating to Strapi 5, to take advantage of its new features and improvements.
Symfony Integration Service
Here's a simplified example of a Symfony service that interacts with Strapi's API:
1// src/Service/StrapiProductService.php
2namespace App\Service;
3
4use Symfony\Contracts\HttpClient\HttpClientInterface;
5use Symfony\Contracts\Cache\CacheInterface;
6
7class StrapiProductService
8{
9 private $httpClient;
10 private $cache;
11 private $strapiUrl;
12
13 public function __construct(HttpClientInterface $httpClient, CacheInterface $cache, string $strapiUrl)
14 {
15 $this->httpClient = $httpClient;
16 $this->cache = $cache;
17 $this->strapiUrl = $strapiUrl;
18 }
19
20 public function getProduct(int $id): array
21 {
22 return $this->cache->get('product_'.$id, function() use ($id) {
23 $response = $this->httpClient->request(
24 'GET',
25 $this->strapiUrl.'/api/products/'.$id.'?populate=*'
26 );
27 return $response->toArray();
28 });
29 }
30
31 public function listProducts(array $filters = []): array
32 {
33 $queryString = http_build_query($filters);
34 $cacheKey = 'products_list_'.md5($queryString);
35
36 return $this->cache->get($cacheKey, function() use ($queryString) {
37 $response = $this->httpClient->request(
38 'GET',
39 $this->strapiUrl.'/api/products?'.$queryString
40 );
41 return $response->toArray();
42 });
43 }
44}
Symfony Controller Example
1// src/Controller/ProductController.php
2namespace App\Controller;
3
4use App\Service\StrapiProductService;
5use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
6use Symfony\Component\HttpFoundation\Response;
7use Symfony\Component\Routing\Annotation\Route;
8
9class ProductController extends AbstractController
10{
11 #[Route('/product/{id}', name: 'product_show')]
12 public function show(int $id, StrapiProductService $productService): Response
13 {
14 $product = $productService->getProduct($id);
15
16 if (!$product) {
17 throw $this->createNotFoundException('Product not found');
18 }
19
20 return $this->render('product/show.html.twig', [
21 'product' => $product,
22 ]);
23 }
24
25 #[Route('/products', name: 'product_list')]
26 public function list(StrapiProductService $productService): Response
27 {
28 $products = $productService->listProducts([
29 'pagination[page]' => 1,
30 'pagination[pageSize]' => 20,
31 'sort' => 'name:asc'
32 ]);
33
34 return $this->render('product/list.html.twig', [
35 'products' => $products,
36 ]);
37 }
38}
Benefits Achieved
Here are some potential positive outcomes of the project:
- Improved Content Management: Marketing teams can effortlessly update product information and promotional content via Strapi’s intuitive interface.
- Enhanced Performance: Implementing caching in the Symfony service reduced Strapi API calls by 60%, significantly improving page load times.
- Scalability: The decoupled architecture allows both systems to scale independently, ensuring better management of resources.
- Flexible Content Modeling: Strapi’s content type builder makes it easy to iterate on product data structures without changing Symfony’s database schema.
Strapi Open Office Hours
If you have any questions about Strapi 5 or just would like to stop by and say hi, you can join us at Strapi's Discord Open Office Hours, Monday through Friday, from 12:30 pm to 1:30 pm CST: Strapi Discord Open Office Hours.
For more details, visit the Strapi documentation and the Symfony documentation.