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()),
// ...
];
}
// ...
}
|
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.
New in Symfony 4.3: URL Helper symfony.com/index.php/blog/new-in-symfony-4-3-url-helper
Tweet thisComments
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
CharlES said on Apr 24, 2019 at 11:35 #1
thanks team