Skip to content

Commit f25896d

Browse files
committed
minor #16176 Add UrlHelper section to HttpFoundation docs (dreadnip)
This PR was squashed before being merged into the 5.4 branch. Discussion ---------- Add UrlHelper section to HttpFoundation docs I was recently looking for a way to generate absolute URLs for assets in a service, and I finally stumbled upon the UrlHelper class after reading [this blog post](https://symfony.com/blog/new-in-symfony-4-3-url-helper), but I couldn't find any mention of it in the docs when searching for absolute_url() or anything related. I then saw [this comment on the original PR](symfony/symfony#30862 (comment)), but saw no such PR for the docs. This is my first contribution to the docs so any feedback is welcome. Commits ------- 5720f50 Add UrlHelper section to HttpFoundation docs
2 parents 6952564 + 5720f50 commit f25896d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

components/http_foundation.rst

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -783,6 +783,38 @@ The following example shows how to detect if the user agent prefers "safe" conte
783783
$response->setContentSafe();
784784

785785
return $response;
786+
787+
UrlHelper
788+
-------
789+
790+
Generating absolute (and relative) URLs for a given path is a common need
791+
in lots of applications. In Twig templates this is trivial thanks to the
792+
absolute_url() and relative_path() functions. The same functionality can
793+
be found in the :class:`Symfony\\Component\\HttpFoundation\\UrlHelper` class,
794+
which can be injected as a service anywhere in your application. This class
795+
provides two public methods called getAbsoluteUrl() and getRelativePath()::
796+
797+
// src/Normalizer/UserApiNormalizer.php
798+
799+
namespace App\Normalizer;
800+
801+
use Symfony\Component\HttpFoundation\UrlHelper;
802+
803+
class UserApiNormalizer
804+
{
805+
private UrlHelper $urlHelper;
806+
807+
public function __construct(UrlHelper $urlHelper)
808+
{
809+
$this->urlHelper = $urlHelper;
810+
}
811+
812+
public function normalize($user)
813+
{
814+
return [
815+
'avatar' => $this->urlHelper->getAbsoluteUrl($user->avatar()->path()),
816+
];
817+
}
786818
}
787819

788820
Learn More

0 commit comments

Comments
 (0)