Skip to content

Commit 5eb0601

Browse files
committed
[HtmlSanitizer] Improve the explanation about injecting sanitizers in services
1 parent 9aedb6e commit 5eb0601

File tree

1 file changed

+43
-2
lines changed

1 file changed

+43
-2
lines changed

html_sanitizer.rst

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,8 +215,49 @@ You can do this by defining a new HTML sanitizer in the configuration:
215215
);
216216
217217
This configuration defines a new ``html_sanitizer.sanitizer.app.post_sanitizer``
218-
service. This service will be :doc:`autowired </service_container/autowiring>`
219-
for services having an ``HtmlSanitizerInterface $appPostSanitizer`` parameter.
218+
service. Now you have two ways of injecting it in any service or controller:
219+
220+
**(1) Use a specific argument name**
221+
222+
Type-hint your construtor/method argument with ``HtmlSanitizerInterface`` and name
223+
the argument using this pattern: "HTML sanitizer name in camelCase". For example, to
224+
inject the ``app.post_sanitizer`` defined earlier, use an argument named ``$appPostSanitizer``::
225+
226+
// src/Controller/ApiController.php
227+
namespace App\Controller;
228+
229+
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
230+
use Symfony\Component\HtmlSanitizer\HtmlSanitizerInterface;
231+
232+
class BlogController extends AbstractController
233+
{
234+
public function __construct(
235+
private HtmlSanitizerInterface $appPostSanitizer,
236+
) {
237+
}
238+
239+
// ...
240+
}
241+
242+
**(2) Use the ``#[Target]`` attribute**
243+
244+
When :ref:`dealing with multiple implementations of the same type <autowiring-multiple-implementations-same-type>`
245+
the ``#[Target]`` attribute helps you select which one to inject. Symfony creates
246+
a target with the same name as the HTML sanitizer::
247+
248+
// ...
249+
use Symfony\Component\DependencyInjection\Attribute\Target;
250+
251+
class BlogController extends AbstractController
252+
{
253+
public function __construct(
254+
#[Target('app.post_sanitizer')]
255+
private HtmlSanitizerInterface $sanitizer,
256+
) {
257+
}
258+
259+
// ...
260+
}
220261

221262
Allow Element Baselines
222263
~~~~~~~~~~~~~~~~~~~~~~~

0 commit comments

Comments
 (0)