Розробка бекенду сайту на PHP (Symfony)
Symfony — не швидкий старт. Це фундамент для проектів, які повинні жити довго, масштабуватися та підтримуватися командами різного складу. Високий поріг входу окуповується передбачуваністю архітектури, строгою типізацією та тим, що компоненти Symfony використовуються всередину Laravel, Drupal, Magento — це індикатор їх якості.
Symfony вибирають для: складних монолітів з багатою доменною логікою, DDD-проектів, високонаванатажених API, enterprise-систем з довгостроковою підтримкою.
Архітектура компонентів
Symfony будується навколо контейнера залежностей (Service Container) та конфігурації через атрибути PHP 8+. Все — сервіс, все — внедряється автоматично:
namespace App\Service;
use App\Repository\ProductRepository;
use App\Event\ProductCreatedEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Psr\Cache\CacheItemPoolInterface;
final class ProductService
{
public function __construct(
private readonly ProductRepository $productRepository,
private readonly EventDispatcherInterface $dispatcher,
private readonly CacheItemPoolInterface $cache,
) {}
public function create(CreateProductDto $dto): Product
{
$product = new Product(
name: $dto->name,
price: Money::of($dto->price, 'USD'),
category: $dto->categoryId
? $this->productRepository->findCategoryOrFail($dto->categoryId)
: null,
);
$this->productRepository->save($product, flush: true);
$this->dispatcher->dispatch(new ProductCreatedEvent($product));
$this->cache->deleteItem("product_{$product->getId()}");
return $product;
}
}
Контролери та маршрути
namespace App\Controller\Api\V1;
use App\Dto\CreateProductDto;
use App\Service\ProductService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[Route('/api/v1/products', name: 'api_products_')]
final class ProductController extends AbstractController
{
public function __construct(private readonly ProductService $productService) {}
#[Route('', name: 'list', methods: ['GET'])]
public function list(ProductListQuery $query): JsonResponse
{
$result = $this->productService->getPaginated($query);
return $this->json($result, context: ['groups' => ['product:list']]);
}
#[Route('', name: 'create', methods: ['POST'])]
#[IsGranted('ROLE_ADMIN')]
public function create(
#[MapRequestPayload] CreateProductDto $dto
): JsonResponse {
$product = $this->productService->create($dto);
return $this->json($product, status: 201, context: ['groups' => ['product:detail']]);
}
#[Route('/{id}', name: 'show', methods: ['GET'])]
public function show(Product $product): JsonResponse
{
return $this->json($product, context: ['groups' => ['product:detail']]);
}
}
Doctrine ORM
Doctrine — повнофункціональна ORM з паттерном Unit of Work. На відміну від Eloquent's Active Record, сутності не знають про БД:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
#[ORM\Entity(repositoryClass: ProductRepository::class)]
#[ORM\Table(name: 'products')]
class Product
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['product:list', 'product:detail'])]
private ?int $id = null;
#[ORM\Column(length: 255)]
#[Groups(['product:list', 'product:detail'])]
private string $name;
#[ORM\Column(type: 'decimal', precision: 10, scale: 2)]
#[Groups(['product:list', 'product:detail'])]
private string $price;
#[ORM\ManyToOne(targetEntity: Category::class, inversedBy: 'products')]
#[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
#[Groups(['product:detail'])]
private ?Category $category = null;
}
Messenger та очереї
Symfony Messenger підтримує: синхронний режим, AMQP, Redis Streams, SQS:
final class SendEmailNotification
{
public function __construct(
public readonly int $userId,
public readonly string $template,
public readonly array $context = []
) {}
}
#[AsMessageHandler]
final class SendEmailNotificationHandler
{
public function __invoke(SendEmailNotification $message): void
{
$user = $this->userRepository->find($message->userId);
$this->mailer->sendTemplate($user->getEmail(), $message->template, $message->context);
}
}
Терміни розробки
Symfony вимагає більше часу на налаштування, але це інвестиція в підтримку:
- Архітектура + DDD domain layer — 1–2 тижні
- Entities + Doctrine migrations — 1 тиждень
- API + Security + DTO — 2–3 тижні
- Messenger + інтеграції — 1–2 тижні
- Тести (PHPUnit + Foundry) — 1–2 тижні
Складний корпоративний сайт або портал: 8–16 тижнів. Symfony окуповується на проектах з планованим зростанням, складною доменною логікою та командою, яка в ньому працює.







