50 phút
Giới thiệu Symfony
Symfony là gì?
Symfony là framework PHP mạnh mẽ, linh hoạt, được sử dụng bởi nhiều dự án lớn như Drupal, Laravel (components), Magento.
Ưu điểm
- Reusable components: Hơn 50 components độc lập
- Flex: Quản lý dependencies linh hoạt
- Doctrine ORM: Tích hợp sẵn
- Console commands: CLI mạnh mẽ
- Testing: PHPUnit tích hợp
- Long-term support: LTS versions
Cài đặt
Yêu cầu
- PHP 8.2+
- Composer
- Symfony CLI (khuyến nghị)
Cài đặt Symfony CLI
# macOS
brew install symfony-cli/tap/symfony-cli
# Linux
curl -sS https://get.symfony.com/cli/installer | bash
# Windows: tải từ https://symfony.com/download
Tạo project mới
symfony new myapp --webapp
cd myapp
symfony serve -d
Cấu trúc project
myapp/
├── bin/
│ └── console
├── config/
│ ├── packages/
│ ├── routes.yaml
│ └── services.yaml
├── migrations/
├── public/
│ └── index.php
├── src/
│ ├── Controller/
│ ├── Entity/
│ ├── Repository/
│ ├── Service/
│ ├── Form/
│ ├── Security/
│ └── Kernel.php
├── templates/
├── tests/
├── translations/
├── var/
├── vendor/
├── .env
├── composer.json
└── symfony.lock
Controller đầu tiên
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class HelloController extends AbstractController
{
#[Route('/hello', name: 'app_hello')]
public function index(): Response
{
return new Response('<h1>Hello, Symfony!</h1>');
}
#[Route('/hello/{name}', name: 'app_hello_name')]
public function greet(string $name): Response
{
return $this->render('hello/greet.html.twig', [
'name' => $name,
]);
}
#[Route('/api/hello', name: 'api_hello', methods: ['GET'])]
public function apiHello(): JsonResponse
{
return $this->json([
'message' => 'Hello from Symfony API',
'timestamp' => time(),
]);
}
}
Twig Template
{# templates/hello/greet.html.twig #}
{% extends 'base.html.twig' %}
{% block title %}Hello {{ name }}{% endblock %}
{% block body %}
<h1>Hello, {{ name }}!</h1>
<p>Welcome to Symfony</p>
{% endblock %}
Console Commands
# Xem tất cả commands
php bin/console list
# Debug routes
php bin/console debug:router
# Clear cache
php bin/console cache:clear
# Generate entity
php bin/console make:entity
# Generate controller
php bin/console make:controller
# Database
php bin/console doctrine:database:create
php bin/console make:migration
php bin/console doctrine:migrations:migrate
Environment Variables
# .env
APP_ENV=dev
APP_SECRET=your-secret-key
DATABASE_URL="postgresql://user:pass@127.0.0.1:5432/myapp?serverVersion=15&charset=utf8"
MAILER_DSN=smtp://localhost:1025
Bài tập thực hành
Hãy tạo controller và routes đầu tiên!