Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions components/http_foundation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down