Skip to content

Add UrlHelper section to HttpFoundation docs #16176

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 3, 2021
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