Valentin Udaltsov
Contributed by Valentin Udaltsov in #30862

Generating absolute (and relative) URLs for a given path is a common need in lots of applications. In Twig templates this is trivial thanks to the absolute_url() and relative_path() functions (don't mistake them for the path() and url() functions that generate URLs using route names).

In Symfony 4.3 we've extracted the internal logic used by the Twig functions into a new class called Symfony\Component\HttpFoundation\UrlHelper that you can inject as a service anywhere in your application. This class provides two public methods called getAbsoluteUrl() and getRelativePath().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use Symfony\Component\HttpFoundation\UrlHelper;

class UserApiNormalizer
{
    private $urlHelper;

    public function __construct(UrlHelper $urlHelper)
    {
        $this->urlHelper = $urlHelper;
    }

    public function normalize($user, $format = null, array $context = [])
    {
        return [
            'avatar' => $this->urlHelper->getAbsoluteUrl($user->avatar()->path()),
            // ...
        ];
    }

    // ...
}
Published in #Living on the edge