Login to bookmark this video
Buy Access to Course
09.

Autowiring Madness

Share this awesome video!

|

Keep on Learning!

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

Ooh, bonus feature! In services.yml, remove arguments and instead just say autowire: true:

17 lines | app/config/services.yml
// ... lines 1 - 5
services:
// ... lines 7 - 10
app.markdown_extension:
// ... lines 12 - 14
#arguments: ['@app.markdown_transformer']
autowire: true

Refresh again. It still works! But how? We didn't tell Symfony what arguments to pass to our constructor? What madness is this!? With autowire: true, Symfony reads the type-hints for each constructor argument:

33 lines | src/AppBundle/Twig/MarkdownExtension.php
// ... lines 1 - 6
class MarkdownExtension extends \Twig_Extension
{
// ... lines 9 - 10
public function __construct(MarkdownTransformer $markdownTransformer)
// ... lines 12 - 31
}

And tries to automatically find the correct service to pass to you. In this case, it saw the MarkdownTransformer type-hint and knew to use the app.markdown_transformer service: since that is an instance of this class. You can also type-hint interfaces.

Tip

The autowiring logic has changed in Symfony 3.3 and higher. For more info, we have a tutorial! https://knpuniversity.com/screencast/symfony-3.3/autowiring-logic

This doesn't always work, but Symfony will give you a big clear exception if it can't figure out what to do. But when it does work, it's a great time saver.

Auto-Escaping a Twig Filter

The HTML is still being escaped - I don't want to finish before we fix that! We could add the |raw filter... but let's do something cooler. Add a third argument to Twig_SimpleFilter: an options array. Add is_safe set to an array containing html:

35 lines | src/AppBundle/Twig/MarkdownExtension.php
// ... lines 1 - 6
class MarkdownExtension extends \Twig_Extension
{
// ... lines 9 - 15
public function getFilters()
{
return [
new \Twig_SimpleFilter('markdownify', array($this, 'parseMarkdown'), [
'is_safe' => ['html']
])
];
}
// ... lines 24 - 33
}

This means it's always safe to output contents of this filter in HTML. Refresh one last time. Beautiful.

Where now!?

Oh my gosh guys! I think you just leveled up: Symfony offense increased by five points. Besides the fact that a lot more things will start making sense in Symfony, you also know everything you need to start organizing your code into service classes - that whole service-oriented architecture thing I was talking about earlier. This will lead you to wonderful applications.

There's really nothing that we can't do now in Symfony. In the next courses, we'll use all this to master new tools like forms and security. Seeya next time!