From 5720f50c52cb8164ba923a240e9c48b6b6e79e81 Mon Sep 17 00:00:00 2001 From: Sander De la Marche Date: Mon, 29 Nov 2021 21:03:00 +0100 Subject: [PATCH] Add UrlHelper section to HttpFoundation docs --- components/http_foundation.rst | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/components/http_foundation.rst b/components/http_foundation.rst index 6154119e715..ec3450a7ed0 100644 --- a/components/http_foundation.rst +++ b/components/http_foundation.rst @@ -783,6 +783,38 @@ The following example shows how to detect if the user agent prefers "safe" conte $response->setContentSafe(); return $response; + +UrlHelper +------- + +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. The same functionality can +be found in the :class:`Symfony\\Component\\HttpFoundation\\UrlHelper` class, +which can be injected as a service anywhere in your application. This class +provides two public methods called getAbsoluteUrl() and getRelativePath():: + + // src/Normalizer/UserApiNormalizer.php + + namespace App\Normalizer; + + use Symfony\Component\HttpFoundation\UrlHelper; + + class UserApiNormalizer + { + private UrlHelper $urlHelper; + + public function __construct(UrlHelper $urlHelper) + { + $this->urlHelper = $urlHelper; + } + + public function normalize($user) + { + return [ + 'avatar' => $this->urlHelper->getAbsoluteUrl($user->avatar()->path()), + ]; + } } Learn More