Build a complete app with Symfony 7 and MySQL

In this comprehensive tutorial, we'll delve into building an expense tracker app using Symfony 7, a powerful PHP framework known for its performance and scalability. Symfony 7 empowers developers to construct robust and scalable web applications effortlessly.
Furthermore, we'll leverage the Symfony 7 Local Web Server to run our application efficiently. To facilitate this, ensure you have the Symfony 7 CLI installed. It's recommended to have PHP version 8.1 or above installed for optimal compatibility and performance.
If you're a PHP developer, chances are you're familiar with Symfony, a widely recognized framework in the PHP ecosystem. For those new to Symfony, let's delve into what makes this framework stand out.
Symfony 7 is a highly acclaimed PHP framework renowned for its prowess in simplifying the web development process. Specifically designed to streamline the creation of web applications, Symfony 7 offers a robust backend framework that emphasizes simplicity and efficiency. Moreover, Symfony 7 isn't limited to PHP; it seamlessly integrates with other languages like JavaScript and Node.js, enhancing its versatility and applicability.
With Symfony 7, developers can craft scalable and intricate web applications with ease, exemplified by notable platforms such as Spotify, which harnesses Symfony's capabilities to deliver exceptional user experiences.
Key features of Symfony include:
- Model-View-Controller (MVC) architecture: Symfony adopts the MVC pattern, providing a structured approach to application development and separating concerns for enhanced maintainability.
- High-performance: Symfony is engineered for optimal performance, ensuring swift and efficient execution of web applications.
- Flexible URI routing: Symfony offers flexible routing mechanisms, allowing developers to define custom URL patterns and manage routing with ease.
- Reusable code: Symfony promotes code reusability through components and bundles, enabling developers to leverage existing codebase efficiently.
- Session management: Symfony simplifies session management, facilitating secure and seamless user interactions across web applications.
- Error logging: Symfony provides comprehensive error logging capabilities, aiding developers in identifying and resolving issues promptly.
- Full-featured database classes: Symfony offers robust database abstractions, facilitating seamless interaction with databases and ensuring efficient data management.
- Open source: Symfony is an open-source framework, fostering collaboration and innovation within the developer community.
Additionally, Symfony 7 boasts a vibrant and active community of developers, ensuring ongoing support, updates, and enhancements. With Symfony's thriving ecosystem, developers can rely on its longevity and continued evolution for years to come.
Let's set up the Symfony 7 application step by step, including creating a new project, connecting it to a MySQL database, adding dependencies, and defining entities.
Step 1: Create Symfony 7 Project
Execute the following command in the terminal to create a new Symfony 7 project named expense_tracker_app
:
composer create-project symfony/skeleton expense_tracker_app
Navigate into the project folder:
cd expense_tracker_app
Step 2: Add Dependencies
Add necessary dependencies for database, template rendering, and form management:
composer require doctrine form twig validator
Step 3: Connect Symfony 7 App to MySQL Database
Create a local environment variable to store database credentials:
cp .env .env.local
Open the newly created .env.local
file and add the MySQL database URL:
DATABASE_URL='mysql://<USERNAME>:<PASSWORD>@<ACCESS_HOST_URL>:3306/expense-tracker?ssl-mode=required&serverVersion=8.0'
MYSQL_ATTR_SSL_CA=/etc/ssl/cert.pem
Make sure to delete the previous value for DATABASE_URL
. Replace <USERNAME>
, <PASSWORD>
, and <ACCESS_HOST_URL>
with appropriate values.
To make the path to your system CA available to Doctrine, add the following to config/packages/doctrine.yaml
:
doctrine:
dbal:
url: '%env(resolve:DATABASE_URL)%'
options: !php/const:PDO::MYSQL_ATTR_SSL_CA: '%env(resolve:MYSQL_ATTR_SSL_CA)%'
Step 4: Add Development Dependencies
For simplifying the development process, add packages that assist in creating sub-components:
composer require --dev maker orm-fixtures
Step 5: Add Entities
Generate entities for the application. Start by creating ExpenseCategory
:
php bin/console make:entity ExpenseCategory
Open src/Entity/ExpenseCategory.php
and update its content as follows:
<?php
namespace App\Entity;
use App\Repository\ExpenseCategoryRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ExpenseCategoryRepository::class)]
class ExpenseCategory {
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column]
private string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function getId()
: ?int {
return $this->id;
}
public function getName()
: string {
return $this->name;
}
}
Next, open src/Repository/ExpenseCategoryRepository.php
and add the following function inside the ExpenseCategoryRepository class:
public function sortedCategories(): QueryBuilder {
return $this->createQueryBuilder('e')->orderBy('e.name', 'ASC');
}
Don’t forget to import the QueryBuilder class.
use Doctrine\ORM\QueryBuilder;
Next, create the Expense entity using the following command:
Next, create Expense
entity:
php bin/console make:entity Expense
Open src/Entity/Expense.php
and update its content as follows:
<?php
namespace App\Entity;
use App\Repository\ExpenseRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: ExpenseRepository::class)]
class Expense {
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne(targetEntity: ExpenseCategory::class)]
#[ORM\JoinColumn(nullable: true)]
private ExpenseCategory $category;
#[ORM\Column]
private float $amount;
public function getCategory()
: ExpenseCategory {
return $this->category;
}
public function setCategory(ExpenseCategory $category)
: void {
$this->category = $category;
}
public function getAmount()
: float {
return $this->amount;
}
public function setAmount(float $amount)
: void {
$this->amount = $amount;
}
}
Add a function to src/Repository/ExpenseRepository.php
:
public function groupedExpenses(): array {
return $this->createQueryBuilder('expense')
->select('category.name, sum(expense.amount) as amount')
->join('expense.category', 'category')
->groupBy('category')
->orderBy('amount', 'DESC')
->getQuery()
->getArrayResult();
}
This function retrieves total expenses per category as an array from the database.
With these steps, you've successfully set up the Symfony 7 application, connected it to a MySQL database, and defined entities for ExpenseCategory
and Expense
.
-
Date: