Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 62 ยท Practice and Review

Practice Exercises

15 graded Symfony practice exercises with solutions on routing, the service container, Twig, Doctrine queries, passwords, roles and CSRF, in runnable PHP stand-ins.

You learn a framework by building with it, but most of Symfony's power comes from ideas that are small enough to write yourself: a router turns a path into a name and parameters, a container builds objects from their constructors, a template engine replaces placeholders and escapes output, a repository turns criteria into safe SQL, a voter answers yes or no. This page gives you 15 exercises that rebuild exactly those ideas in plain PHP, so you can run them right here.

Symfony itself cannot run in the browser, so the exercises use stand-ins: small functions and classes that behave like the real component for the case at hand. What you practice is the logic, and every exercise names the real Symfony feature it mirrors. Each one has a task, an editor with starter code and a hidden solution.

  • The starter code runs as given. Functions you must write are stubs; the comments show the output you should get once your code works. Replace the stub, press Run, and compare.
  • Try first, peek later. A few minutes of being stuck is where the learning happens.
  • Compare, don't copy. Your solution may look different from ours and still be right.
  • Read the errors. PHP runs with all errors reported, so notices and warnings appear in the output. Treat each one as a bug.

PHP basics are covered in the PHP tutorial; here we assume you know functions, classes and arrays.

Routing

These exercises practice ideas from Routing with Attributes, Route Parameters and Requirements and Generating URLs.

1. Match a path (Beginner)

Write matchRoute(array $routes, string $path): ?array. $routes maps a route name to a pattern with . Return ['route' => name, 'params' => [...]] for the first route that matches the whole path, or null. A placeholder matches anything except a slash.

PHP Exercise 1: Match a path

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.

Show solution
PHP
function matchRoute(array $routes, string $path): ?array
{
    foreach ($routes as $name => $pattern) {
        $regex = '#^' . preg_replace('/\{(\w+)\}/', '(?P<$1>[^/]+)', $pattern) . '$#';
        if (preg_match($regex, $path, $matches)) {
            return [
                'route' => $name,
                'params' => array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY),
            ];
        }
    }

    return null;
}

Each becomes a named capture group, and preg_match fills $matches with both numbered and named keys. array_filter with ARRAY_FILTER_USE_KEY keeps only the string keys, which are the parameters. The real Symfony router also quotes literal parts of the pattern and compiles all routes once.

2. Generate a URL (Intermediate)

Write generate(array $routes, string $name, array $params = []): string. Fill the placeholders from $params (URL-encoded with rawurlencode), and append the remaining parameters as a query string. Throw InvalidArgumentException with the messages from the comments when the route or a required parameter is missing.

PHP Exercise 2: Generate a URL

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.

Show solution
PHP
function generate(array $routes, string $name, array $params = []): string
{
    $pattern = $routes[$name] ?? throw new InvalidArgumentException("Route \"{$name}\" does not exist");

    $path = preg_replace_callback('/\{(\w+)\}/', function (array $m) use ($name, &$params): string {
        if (!array_key_exists($m[1], $params)) {
            throw new InvalidArgumentException("Missing parameter \"{$m[1]}\" for route \"{$name}\"");
        }
        $value = rawurlencode((string) $params[$m[1]]);
        unset($params[$m[1]]);

        return $value;
    }, $pattern);

    return $params === [] ? $path : $path . '?' . http_build_query($params);
}

The closure takes $params by reference and removes every parameter it uses, so whatever is left over is exactly the extra data for the query string. This is what UrlGeneratorInterface::generate() does, with a few more details such as defaults and requirements.

3. 404 or 405? (Intermediate)

Write dispatch(array $routes, string $method, string $path): array. Routes are [method, pattern, handler] triples. Return [200, handler] for a match. If the path matches a route only with other methods, return [405, 'Allow: ...'] listing those methods in route order. Otherwise return [404, null].

PHP Exercise 3: 404 or 405?

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.

Show solution
PHP
function dispatch(array $routes, string $method, string $path): array
{
    $allowed = [];
    foreach ($routes as [$routeMethod, $pattern, $handler]) {
        $regex = '#^' . preg_replace('/\{(\w+)\}/', '[^/]+', $pattern) . '$#';
        if (!preg_match($regex, $path)) {
            continue;
        }
        if ($routeMethod === $method) {
            return [200, $handler];
        }
        $allowed[] = $routeMethod;
    }

    return $allowed === [] ? [404, null] : [405, 'Allow: ' . implode(', ', $allowed)];
}

Collecting the methods of path matches is the whole trick: the same path with a different verb is "method not allowed", not "not found". Symfony throws MethodNotAllowedException carrying the allowed methods.

Services and the container

These practice Services and the Service Container, Autowiring and Dependency Injection and Tags, Decorators and Service Locators.

4. A shared-service container (Beginner)

Implement Container::set() and Container::get(). A factory is a callable that receives the container. get() must call the factory only once per id and return the same object afterwards, and throw LogicException('Service "x" not found') for unknown ids.

PHP Exercise 4: A shared-service container

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.

Show solution
PHP
final class Container
{
    /** @var array<string, callable> */
    private array $factories = [];
    /** @var array<string, object> */
    private array $instances = [];

    public function set(string $id, callable $factory): void
    {
        $this->factories[$id] = $factory;
    }

    public function get(string $id): object
    {
        if (isset($this->instances[$id])) {
            return $this->instances[$id];
        }
        $factory = $this->factories[$id] ?? throw new LogicException("Service \"{$id}\" not found");

        return $this->instances[$id] = $factory($this);
    }
}

Storing the first result in $instances makes every service a shared instance, which is the default in Symfony. Passing $this to the factory lets one service ask for the others it depends on.

5. Autowire with an alias (Intermediate)

Write autowire(string $class, array $aliases): object. Use Reflection to read the constructor. For a class-typed parameter, resolve its type through $aliases first (interface to implementation) and build it recursively. For a scalar with a default value, use the default. Anything else throws a LogicException.

PHP Exercise 5: Autowire with an alias

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.

Show solution
PHP
function autowire(string $class, array $aliases): object
{
    $class = $aliases[$class] ?? $class;
    $reflection = new ReflectionClass($class);
    if (!$reflection->isInstantiable()) {
        throw new LogicException("Cannot autowire \"{$class}\": no alias and it is not instantiable");
    }

    $args = [];
    foreach ($reflection->getConstructor()?->getParameters() ?? [] as $param) {
        $type = $param->getType();
        if ($type instanceof ReflectionNamedType && !$type->isBuiltin()) {
            $args[] = autowire($type->getName(), $aliases);
        } elseif ($param->isDefaultValueAvailable()) {
            $args[] = $param->getDefaultValue();
        } else {
            throw new LogicException("Cannot autowire argument \${$param->getName()} of \"{$class}\"");
        }
    }

    return $reflection->newInstanceArgs($args);
}

isInstantiable() is false for interfaces and abstract classes, which is exactly the situation where an alias is missing. Symfony does the same analysis once, at compile time, and generates plain new calls.

6. Find the cycle (Intermediate)

Write buildOrder(string $class, array $stack = [], array &$order = []): array. It returns the classes in the order they must be constructed (dependencies first, each class once), by walking constructor type-hints. If it meets a class that is already on the current path, throw LogicException with the message Circular reference: A -> B -> C -> A showing the path.

PHP Exercise 6: Find the cycle

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.

Show solution
PHP
function buildOrder(string $class, array $stack = [], array &$order = []): array
{
    if (in_array($class, $stack, true)) {
        throw new LogicException('Circular reference: ' . implode(' -> ', [...$stack, $class]));
    }
    if (in_array($class, $order, true)) {
        return $order;
    }

    foreach ((new ReflectionClass($class))->getConstructor()?->getParameters() ?? [] as $param) {
        buildOrder($param->getType()->getName(), [...$stack, $class], $order);
    }
    $order[] = $class;

    return $order;
}

$stack is the path from the root to the current class, so a class that appears on it again is a cycle. $order is shared by reference and collects classes after their dependencies (post-order), which is a valid construction order. Symfony's compiler pass detects circular references in the same way and prints the path.

7. A tagged iterator (Intermediate)

Services can carry tags with attributes such as a priority. Write taggedServices(array $definitions, string $tag): array that returns the services carrying $tag, highest priority first (default priority 0; equal priorities keep their definition order). Then the script chains the formatters over a string.

PHP Exercise 7: A tagged iterator

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.

Show solution
PHP
/** @return list<callable> */
function taggedServices(array $definitions, string $tag): array
{
    $matching = array_filter($definitions, fn (array $d) => isset($d['tags'][$tag]));

    uasort($matching, fn (array $a, array $b) =>
        ($b['tags'][$tag]['priority'] ?? 0) <=> ($a['tags'][$tag]['priority'] ?? 0));

    return array_values(array_map(fn (array $d) => $d['service'], $matching));
}

uasort is stable since PHP 8.0, so services with equal priority keep their original order, as in Symfony. The result is what #[AutowireIterator('app.formatter')] hands to a constructor, so one class can run every formatter without knowing any of them.

Twig

These practice Twig Basics and Twig Functions, Filters and Tests.

8. Escaping by default (Beginner)

Write render(string $template, array $vars): string. Replace {{ name }} with the variable, HTML-escaped. {{ name|raw }} inserts it unescaped. A variable that does not exist throws RuntimeException with the message Variable "x" does not exist.

PHP Exercise 8: Escaping by default

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.

Show solution
PHP
function render(string $template, array $vars): string
{
    return preg_replace_callback(
        '/\{\{\s*(\w+)\s*(\|\s*raw\s*)?\}\}/',
        function (array $m) use ($vars): string {
            if (!array_key_exists($m[1], $vars)) {
                throw new RuntimeException("Variable \"{$m[1]}\" does not exist.");
            }
            $value = (string) $vars[$m[1]];

            return isset($m[2]) ? $value : htmlspecialchars($value, ENT_QUOTES);
        },
        $template,
    );
}

Escaping is the default and raw is the explicit opt-out, which is what makes Twig safe: you must write the dangerous thing on purpose. Twig also fails loudly on unknown variables when strict_variables is on, which is the default in debug mode.

9. A filter pipeline (Intermediate)

Extend the idea: {{ name|trim|upper }} applies filters from left to right, then the result is escaped. Write renderFilters(string $template, array $vars): string supporting trim, upper, lower and length. An unknown filter throws RuntimeException('Unknown filter "x".').

PHP Exercise 9: A filter pipeline

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.

Show solution
PHP
function renderFilters(string $template, array $vars): string
{
    $filters = [
        'trim' => 'trim',
        'upper' => 'strtoupper',
        'lower' => 'strtolower',
        'length' => 'strlen',
    ];

    return preg_replace_callback('/\{\{\s*(\w+)((?:\s*\|\s*\w+)*)\s*\}\}/', function (array $m) use ($vars, $filters): string {
        $value = $vars[$m[1]] ?? throw new RuntimeException("Variable \"{$m[1]}\" does not exist.");
        foreach (array_filter(array_map('trim', explode('|', $m[2]))) as $name) {
            $function = $filters[$name] ?? throw new RuntimeException("Unknown filter \"{$name}\".");
            $value = $function($value);
        }

        return htmlspecialchars((string) $value, ENT_QUOTES);
    }, $template);
}

The second capture group holds all the |filter pieces at once; splitting it on | gives the names in order. The escape happens last, after the filters, so upper sees the raw text. Real Twig compiles templates to PHP, but the order of operations is the same.

10. A for loop with else (Intermediate)

Write renderLoop(string $template, array $vars): string for {% for item in items %}...{{ item }}...{% else %}...{% endfor %}. Inside the body, {{ item }} (the loop variable name) is replaced by the escaped element. If the list is empty, output the else part instead.

PHP Exercise 10: A for loop with else

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.

Show solution
PHP
function renderLoop(string $template, array $vars): string
{
    $pattern = '/\{% for (\w+) in (\w+) %\}(.*?)(?:\{% else %\}(.*?))?\{% endfor %\}/s';

    return preg_replace_callback($pattern, function (array $m) use ($vars): string {
        [, $item, $list, $body] = $m;
        $else = $m[4] ?? '';
        $items = $vars[$list] ?? [];
        if ($items === []) {
            return $else;
        }

        $out = '';
        foreach ($items as $value) {
            $out .= preg_replace(
                '/\{\{\s*' . preg_quote($item, '/') . '\s*\}\}/',
                htmlspecialchars((string) $value, ENT_QUOTES),
                $body,
            );
        }

        return $out;
    }, $template);
}

The s flag lets . match newlines, and the lazy .*? stops at the first else or endfor. This stand-in cannot nest loops; real Twig has a proper lexer and parser for that, but the for ... else behavior is the same.

Doctrine and data

These practice Repositories and Queries and Doctrine Performance and Pitfalls.

11. A safe findBy (Intermediate)

Write findBy(PDO $pdo, array $criteria, array $orderBy = [], ?int $limit = null): array over the book table. Only the fields id, title, author and year may be used; any other field throws InvalidArgumentException('Unknown field "x".'). Values must be bound parameters, never pasted into the SQL. Order directions are ASC or DESC.

PHP Exercise 11: A safe findBy

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.

Show solution
PHP
function findBy(PDO $pdo, array $criteria, array $orderBy = [], ?int $limit = null): array
{
    $check = function (string $field): string {
        return in_array($field, FIELDS, true) ? $field : throw new InvalidArgumentException("Unknown field \"{$field}\".");
    };

    $sql = 'SELECT * FROM book';
    $params = [];
    if ($criteria !== []) {
        $parts = [];
        foreach ($criteria as $field => $value) {
            $parts[] = $check($field) . ' = ?';
            $params[] = $value;
        }
        $sql .= ' WHERE ' . implode(' AND ', $parts);
    }
    if ($orderBy !== []) {
        $parts = [];
        foreach ($orderBy as $field => $direction) {
            $parts[] = $check($field) . (strtoupper($direction) === 'DESC' ? ' DESC' : ' ASC');
        }
        $sql .= ' ORDER BY ' . implode(', ', $parts);
    }
    if ($limit !== null) {
        $sql .= ' LIMIT ' . $limit;
    }

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

Values are bound, while identifiers (column names, directions) cannot be bound and therefore come from a whitelist. $limit is typed ?int, so it is safe to append. Doctrine's findBy() and QueryBuilder apply the same rule: field names are checked against the mapping and values travel as parameters.

12. Fix the N+1 (Advanced)

The starter loads every post and then runs one extra query per post to fetch its comments. Rewrite loadPostsWithComments so it runs exactly two queries however many posts there are: one for the posts and one for all their comments with WHERE post_id IN (...). The printed result must stay the same; only the query count changes.

PHP Exercise 12: Fix the N+1

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.

Show solution
PHP
function loadPostsWithComments(Db $db): array
{
    $posts = $db->rows('SELECT id, title FROM post ORDER BY id');
    if ($posts === []) {
        return [];
    }

    $ids = array_column($posts, 'id');
    $placeholders = implode(', ', array_fill(0, count($ids), '?'));
    $byPost = [];
    foreach ($db->rows("SELECT post_id, body FROM comment WHERE post_id IN ({$placeholders}) ORDER BY id", $ids) as $row) {
        $byPost[$row['post_id']][] = $row['body'];
    }

    $result = [];
    foreach ($posts as $post) {
        $result[$post['title']] = $byPost[$post['id']] ?? [];
    }

    return $result;
}

Two queries replace 1 + N. In Doctrine you get the same effect with a fetch join (->leftJoin('p.comments', 'c')->addSelect('c')), which loads posts and comments in one query, at the price of repeating each post row per comment; loading the collection with a separate IN query, as here, avoids that repetition. The profiler's query count is how you notice the problem in real life.

Security

These practice Security: Users and Firewalls, Login Forms and Authenticators, Authorization: Roles and Voters and Handling Submission and CSRF.

13. Hash and verify (Intermediate)

Implement register() and login() in UserStore. Store only a hash created with password_hash (use bcrypt with cost 4 here to keep the example quick; use the default cost in production). login() returns Welcome <email> on success and exactly Invalid credentials. for both a wrong password and an unknown email, and it must still run a hash comparison for unknown users so that response time does not reveal which emails exist.

PHP Exercise 13: Hash and verify

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.

Show solution
PHP
public function register(string $email, string $password): void
{
    $this->hashes[$email] = password_hash($password, PASSWORD_BCRYPT, ['cost' => 4]);
}

public function login(string $email, string $password): string
{
    $hash = $this->hashes[$email]
        ?? password_hash('dummy', PASSWORD_BCRYPT, ['cost' => 4]);   // same work for unknown users

    $valid = password_verify($password, $hash) && isset($this->hashes[$email]);

    return $valid ? "Welcome {$email}" : 'Invalid credentials.';
}

password_hash adds a random salt, so two users with the same password get different hashes, and password_verify reads the salt and cost from the hash itself. Using one error message for both failures stops attackers from collecting valid email addresses. Symfony's UserPasswordHasherInterface wraps the same functions and adds needsRehash() so hashes upgrade automatically when you raise the cost. In real code, create the dummy hash once, not on every call.

14. A role hierarchy (Intermediate)

Write hasRole(array $hierarchy, array $userRoles, string $needed): bool. $hierarchy maps a role to the roles it includes, and inclusion is transitive. Take care not to loop forever if someone configures a cycle.

PHP Exercise 14: A role hierarchy

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.

Show solution
PHP
function hasRole(array $hierarchy, array $userRoles, string $needed): bool
{
    $seen = [];
    $queue = $userRoles;

    while ($queue !== []) {
        $role = array_shift($queue);
        if ($role === $needed) {
            return true;
        }
        if (isset($seen[$role])) {
            continue;
        }
        $seen[$role] = true;
        array_push($queue, ...($hierarchy[$role] ?? []));
    }

    return false;
}

This is a breadth-first search through the role graph; the $seen set guarantees that every role is expanded once, so even a cyclic configuration terminates. Symfony's RoleHierarchy builds the same reachable set from the role_hierarchy option in security.yaml.

15. A CSRF token manager (Advanced)

Write CsrfTokenManager with token(string $tokenId): string and isValid(string $tokenId, string $token): bool. A token is the HMAC-SHA256 of the token id, keyed with the secret and the session id, encoded as URL-safe base64 without padding. Compare with a constant-time function.

PHP Exercise 15: A CSRF token manager

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.

Show solution
PHP
public function token(string $tokenId): string
{
    $mac = hash_hmac('sha256', $tokenId, $this->secret . '|' . $this->sessionId, true);

    return rtrim(strtr(base64_encode($mac), '+/', '-_'), '=');
}

public function isValid(string $tokenId, string $token): bool
{
    return hash_equals($this->token($tokenId), $token);
}

A SHA-256 MAC is 32 bytes, which is 43 characters in base64 without padding. Binding the token to the session id means a token stolen from one session is useless in another, and binding it to the token id means a token for deleting task 5 cannot delete task 6. hash_equals compares in constant time so the check cannot leak how many characters matched. Symfony's CsrfTokenManager and the csrf_token() Twig function work with the same idea, with random per-session tokens stored in the session.

Where to go next

If you got stuck, go back to the lesson linked at the top of the group, run its stand-in again and change one thing at a time. When the exercises feel easy, build one of the projects: A Blog, A Task Manager, A Bookstore JSON API or An Async Report Generator. Extend your solutions too: make the router in exercise 1 enforce a requirements regex per placeholder, or let the container in exercise 4 detect circular factories.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Exercise 3: which status should a request get when the path exists but only for other HTTP methods?

    The resource exists, so it is not a 404; the verb is wrong, which is 405. The Allow header tells clients which methods they may use.
  2. 2. Exercise 11: why are column names whitelisted instead of bound as parameters?

    A bound parameter is always treated as a value. Identifiers have to be chosen by the code, so they come from a fixed list.
  3. 3. Exercise 12: what is the main cost of the N+1 pattern?

    One query for the list plus one per row means 100 posts cost 101 round trips, even though two queries would do.
  4. 4. Exercise 13: why does login return the same message for an unknown email and a wrong password?

    Different messages (or noticeably different response times) let someone probe which accounts exist.
  5. 5. Exercise 15: what does binding a CSRF token to the session id achieve?

    The MAC covers the session id, so a token generated for one session fails validation in any other.

Summary

  • Routing is pattern matching plus a clear difference between 404 and 405; URL generation is the reverse and keeps leftover parameters for the query string.
  • A container creates each service once and a reflection-based autowirer needs aliases for interfaces; cycles are found by tracking the current path.
  • Template engines escape by default and make unsafe output an explicit choice; filters run left to right and escaping comes last.
  • Queries bind values, whitelist identifiers and avoid one query per row.
  • Store password hashes only, give one error for all login failures, expand roles transitively and tie CSRF tokens to the session and the action.

Finish the track with the Symfony Interview Questions.