Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages in full color showing how to combine Symfony with Docker, APIs, queues & async tasks, Webpack, Single-Page Applications, etc.

Buy printed version

New in Symfony 4.3: URL Helper

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()),
            // ...
        ];
    }

    // ...
}

Comments

Simple, but necessary
thanks team
Nice one!
👍
Cool one :)

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.