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