New in Symfony 4.3: URL Helper
April 23, 2019 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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()),
// ...
];
}
// ...
}
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
thanks team