Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 62 ยท Projects

Project: A Blog

Build a Symfony blog in stages - Post and Comment entities, repository pagination, controllers, Twig templates and a comment form - with a runnable core stand-in.

A blog is the classic first real application: posts have readable URLs, the home page shows the newest posts a page at a time, readers can comment, and everything lives in a database. It touches almost every part of the framework you have learned so far, which makes it the right first project.

In this lesson you plan the blog, see the real Symfony code for each layer (entities, repository, controllers, Twig, form), and then run a plain-PHP stand-in of the same core: a slugger, a repository with pagination, a router, a tiny template function and a validated comment form with the POST-redirect-GET pattern. Symfony cannot run in the browser here, so the real code is read-only. You can copy it into a project created with symfony new blog --webapp, as shown in Installing Symfony and the CLI.

The plan

Two entities and four routes are enough:

Method Path Route name Purpose
GET / and /?page=2 blog_index newest posts, five per page
GET /posts/{slug} blog_show one post with its comments
POST /posts/{slug}/comments blog_comment add a comment, then redirect
GET /posts/new blog_new author form (needs a login, see the next project; give it a higher priority than blog_show, so new is not read as a slug)
flowchart LR
    R["Request"] --> C["BlogController"]
    C --> P["PostRepository"]
    P --> DB[("Database")]
    C --> F["CommentType form"]
    C --> T["Twig template"]
    T --> S["Response"]

A controller coordinates the repository, the form and the template; none of them knows about the others.

Entities

A Post has a unique slug that is the public name of the page, and a one-to-many relation to comments (see Relations for the owning side rules):

PHP
<?php
namespace App\Entity;

use App\Repository\PostRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

#[ORM\Entity(repositoryClass: PostRepository::class)]
class Post
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 160)]
    #[Assert\NotBlank, Assert\Length(max: 160)]
    private string $title = '';

    #[ORM\Column(length: 180, unique: true)]
    private string $slug = '';

    #[ORM\Column(type: 'text')]
    #[Assert\NotBlank]
    private string $body = '';

    #[ORM\Column]
    private \DateTimeImmutable $publishedAt;

    /** @var Collection<int, Comment> */
    #[ORM\OneToMany(mappedBy: 'post', targetEntity: Comment::class, cascade: ['persist'], orphanRemoval: true)]
    #[ORM\OrderBy(['createdAt' => 'ASC'])]
    private Collection $comments;

    public function __construct()
    {
        $this->publishedAt = new \DateTimeImmutable();
        $this->comments = new ArrayCollection();
    }

    // getters and setters omitted: make:entity generates them
}
PHP
<?php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

#[ORM\Entity]
class Comment
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;

    #[ORM\ManyToOne(inversedBy: 'comments')]
    #[ORM\JoinColumn(nullable: false)]
    private ?Post $post = null;

    #[ORM\Column(length: 80)]
    #[Assert\NotBlank, Assert\Length(max: 80)]
    private string $author = '';

    #[ORM\Column(type: 'text')]
    #[Assert\NotBlank, Assert\Length(min: 5, max: 2000)]
    private string $body = '';

    #[ORM\Column]
    private \DateTimeImmutable $createdAt;
}

Generate the classes with php bin/console make:entity Post, then create and run the migration with make:migration and doctrine:migrations:migrate (Migrations). Slugs are produced by the SluggerInterface service, which you inject; call $slugger->slug($title)->lower() when the post is created and never change it afterwards, because other sites link to it.

The repository and pagination

Put the query in the repository, not in the controller. A page of posts needs an ordered query with setFirstResult and setMaxResults; Doctrine's Paginator also counts the total correctly when joins are involved (Repositories and Queries):

PHP
<?php
namespace App\Repository;

use App\Entity\Post;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Doctrine\Persistence\ManagerRegistry;

/** @extends ServiceEntityRepository<Post> */
class PostRepository extends ServiceEntityRepository
{
    public const PER_PAGE = 5;

    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Post::class);
    }

    public function findLatest(int $page): Paginator
    {
        $query = $this->createQueryBuilder('p')
            ->orderBy('p.publishedAt', 'DESC')
            ->addOrderBy('p.id', 'DESC')
            ->setFirstResult(($page - 1) * self::PER_PAGE)
            ->setMaxResults(self::PER_PAGE)
            ->getQuery();

        return new Paginator($query);
    }
}

The second orderBy is a tie-breaker: posts published at the same moment must have a stable order, otherwise a post can appear on two pages or none. The stand-in below does the same with plain SQL on SQLite and includes the slug logic, so you can see the rules in action.

PHP Stage 1: slugs, a repository and pagination

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice three behaviors that the real application needs as well: a duplicate title gets a numeric suffix instead of violating the unique index, the page number is clamped so ?page=99 shows the last page instead of an empty one (in Symfony you can alternatively throw NotFoundHttpException), and the order is fully determined.

Controller and templates

The controller reads the page number, asks the repository and renders a template. #[MapEntity] loads the post from the placeholder and automatically produces a 404 if it does not exist (Route Parameters and Requirements):

PHP
<?php
namespace App\Controller;

use App\Entity\Comment;
use App\Entity\Post;
use App\Form\CommentType;
use App\Repository\PostRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapQueryParameter;
use Symfony\Component\Routing\Attribute\Route;

final class BlogController extends AbstractController
{
    #[Route('/', name: 'blog_index', methods: ['GET'])]
    public function index(PostRepository $posts, #[MapQueryParameter] int $page = 1): Response
    {
        $paginator = $posts->findLatest(max(1, $page));

        return $this->render('blog/index.html.twig', [
            'posts' => $paginator,
            'page' => $page,
            'pages' => (int) ceil(count($paginator) / PostRepository::PER_PAGE),
        ]);
    }

    #[Route('/posts/{slug}', name: 'blog_show', methods: ['GET', 'POST'])]
    public function show(
        #[MapEntity(mapping: ['slug' => 'slug'])] Post $post,
        Request $request,
        EntityManagerInterface $em,
    ): Response {
        $comment = new Comment();
        $form = $this->createForm(CommentType::class, $comment);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $post->addComment($comment);
            $em->flush();
            $this->addFlash('success', 'Thanks for your comment!');

            return $this->redirectToRoute('blog_show', ['slug' => $post->getSlug()]);
        }

        return $this->render('blog/show.html.twig', [
            'post' => $post,
            'form' => $form,
        ], new Response(status: $form->isSubmitted() ? 422 : 200));
    }
}

The redirect after a successful POST is the POST-redirect-GET pattern: it stops the browser from re-sending the comment when the visitor reloads. Returning status 422 for an invalid form tells Turbo and other clients that the page shows validation errors.

The form class describes the two fields; the validation rules come from the attributes on the entity:

PHP
<?php
namespace App\Form;

use App\Entity\Comment;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class CommentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('author', TextType::class)
            ->add('body', TextareaType::class, ['label' => 'Your comment']);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(['data_class' => Comment::class]);
    }
}

Twig then renders the list, the post and the form. Autoescaping makes the comment text safe by default (Twig Basics):

TWIG
{# templates/blog/show.html.twig #}
{% extends 'base.html.twig' %}

{% block title %}{{ post.title }}{% endblock %}

{% block body %}
    <article>
        <h1>{{ post.title }}</h1>
        <p>{{ post.body|nl2br }}</p>
    </article>

    <h2>{{ post.comments|length }} comments</h2>
    {% for comment in post.comments %}
        <p><strong>{{ comment.author }}</strong>: {{ comment.body }}</p>
    {% else %}
        <p>No comments yet.</p>
    {% endfor %}

    {{ form(form) }}
{% endblock %}

The core as a runnable stand-in

The next TryIt rebuilds the request handling of the blog in plain PHP: a router that compiles placeholders, a repository interface with an in-memory implementation (the same idea that lets you swap a fake repository in a test), a template function that escapes values, and the comment form with validation and POST-redirect-GET. It then simulates six requests.

PHP Stage 2: router, controller, template and comment form

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the output from top to bottom: the invalid comment gets a 422 with messages and is not stored, the valid one gets a 302 to the post page, and the next GET shows the comment with its HTML escaped. A path that matches a route with the wrong method gives 405, an unknown slug gives 404. Real Symfony does all of this for you, but each step in the stand-in has a direct counterpart: routing in the Router, the MapEntity 404 in findBySlug, $form->isValid() in validateComment, and Twig's autoescape in e().

Next steps

Extend the blog to practice what you have learned:

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the repository order posts by publishedAt and then by id?

    Without a tie-breaker the database may order equal values differently between queries, so a post can show up on two pages or on none.
  2. 2. What problem does POST-redirect-GET solve?

    After a successful POST the server answers with a redirect, so the browser's current page is a GET and a reload does not repeat the submission.
  3. 3. A visitor opens /posts/does-not-exist. With #[MapEntity] on the Post argument, what happens?

    When MapEntity cannot find a matching row for a required argument it throws a NotFoundHttpException, which becomes a 404.
  4. 4. In the stand-in, why does the stored script tag in the comment show up as harmless text in the page?

    Escaping on output (htmlspecialchars here, autoescape in Twig) turns markup into harmless text.

Summary

  • A blog needs two entities, a repository with a paginated query, a controller, templates and a form; keep each in its own layer.
  • Slugs are public identifiers: make them unique and never change them.
  • Order paginated queries by a unique tie-breaker and handle out-of-range pages.
  • Validate on the server, answer with 422 on errors and redirect after success.
  • Escape on output; Twig does it automatically.
  • Stand-ins with interfaces (an in-memory repository) make the core logic easy to test without a database.

Next, add users, permissions and ownership in Project: A Task Manager.