// composer.json
{
"require": {
"php": "^7.1.3",
"ext-iconv": "*",
"composer/package-versions-deprecated": "^1.11", // 1.11.99
"doctrine/doctrine-bundle": "^1.6.10", // 1.10.2
"doctrine/doctrine-migrations-bundle": "^1.3|^2.0", // v2.0.0
"doctrine/orm": "^2.5.11", // v2.7.2
"knplabs/knp-markdown-bundle": "^1.7", // 1.7.0
"knplabs/knp-time-bundle": "^1.8", // 1.8.0
"nexylan/slack-bundle": "^2.0,<2.2.0", // v2.0.0
"php-http/guzzle6-adapter": "^1.1", // v1.1.1
"sensio/framework-extra-bundle": "^5.1", // v5.1.4
"stof/doctrine-extensions-bundle": "^1.3", // v1.3.0
"symfony/asset": "^4.0", // v4.0.4
"symfony/console": "^4.0", // v4.0.14
"symfony/flex": "^1.0", // v1.21.6
"symfony/framework-bundle": "^4.0", // v4.0.14
"symfony/lts": "^4@dev", // dev-master
"symfony/twig-bundle": "^4.0", // v4.0.4
"symfony/web-server-bundle": "^4.0", // v4.0.4
"symfony/yaml": "^4.0" // v4.0.14
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.0", // 3.0.2
"easycorp/easy-log-handler": "^1.0.2", // v1.0.4
"fzaninotto/faker": "^1.7", // v1.7.1
"symfony/debug-bundle": "^3.3|^4.0", // v4.0.4
"symfony/dotenv": "^4.0", // v4.0.14
"symfony/maker-bundle": "^1.0", // v1.4.0
"symfony/monolog-bundle": "^3.0", // v3.1.2
"symfony/phpunit-bridge": "^3.3|^4.0", // v4.0.4
"symfony/stopwatch": "^3.3|^4.0", // v4.0.4
"symfony/var-dumper": "^3.3|^4.0", // v4.0.4
"symfony/web-profiler-bundle": "^3.3|^4.0" // v4.0.4
}
}
47 Comments
so there, I am using the ServiceSubscriberInterface to inject into my Command the Psr Container. Then I want to enable some services in the Command, namely all the messenger transport I have defined: "transport_high", "transport_normal". I do this because I want to call the getMessageCount() on each transport. BUT, the problem is that I get this error: The service "App\Command\WorkCommand" has a dependency on a non-existent service "Symfony\Component\Messenger\Transport\TransportInterface". What service is the transport service then? And how can I access all of the transports? Thank you!
so this is what I've done intuitively
services.yaml
Command class:
and it works.
Can you shed more light on it and maybe direct me to some documentation covering this edge case please?
Hey Francisc !
Excellent question - and nice job finding the solution! So, there are 2 separate things going on... and I don't want to confuse them.
1) Pretend for a moment that we're not using a service subscriber, because the first "thing going on" has nothing to do with service subscribers. In Symfony's container, there are many services. It depends on your app, but let's pretend that there are 200 services. The majority of these services are not "meant" for you to use directly. I mean, you can use them directly, but Symfony makes it "not very easy". Specifically, if Symfony "wants" you to use a service, it configures an "autowiring alias" for it. For example, Symfony DOES want you to use the
loggerservice directly. So it creates an alias fromPsr\Log\LoggerInterfacetologgerso that you can type-hint Logger and get that service. But Symfony doesn't do this for all services in the container. If you have 200 services in the container, probably only about 50 of them have "autowiring aliases". You can use those other 150 services if you want to, but you need to do more work. Specifically, you need to manually "wire" them into a service. Usually, that would look like this:In this case, I'm pretending that this
some_service_idservice is a service that I want to access, but it does not have an autowiring alias. So, I configure it specifically on the service: Symfony will know to pass this service to my$someArgumentNameargument (you could also useargumentsinstead ofbind- they are equivalent in most cases.2) The above description is the really important piece to all of this. Now let's talk about service subscribers :). By default, they work via autowiring: your
getSubscribedServicesmethod returns an array of autowiring type-hints that you want to be included in your service locator. If you use a interface/class that doesn't have an autowireable alias, it won't work. That's what's happening with the transports. It's not that common to need to interact with transport service directly. And so, autowiring alias are not made available. This is why it didn't work originally. Your solution above (which is correct) is how you explicitly configure a service inside a service locator when it doesn't have an autowireable alias.Phew! I hope that helps! The big picture is that you're trying to reference services that are not autowireable. You could also make them autowireable with global binds:
Let me know if that demystifies it! Fun stuff!
Cheers!
Hello,
Is this solution of lazy loading twig extensions a new way to do it ?
Thanks !
Hy Guys, which is the diference between Psr\Container\ContainerInterface and Symfony\Component\DependencyInjection\ContainerInterface ? Thanks!
Hey Beis
It's quite simple.
Psr\Container\ContainerInterfaceis more low level Interface which describes basic PSR Container, howeverSymfony\Component\DependencyInjection\ContainerInterfaceis more complex and of course it extendsPsr\Container\ContainerInterface. If you not sure which one to use for autowire you could choose one fromPsr\. In Symfony both interfaces are aliases toserver_containerand you will get the same object, only IDE autocompletion will be different a little.Cheers!
Hello there ,
Thanks for this tutorial I didn't see it until you linked it from another video, I'm going to apply it right now. But now I have for me one of my big doubts, I'm going to have a hard time explaining it because I don't know how to name it, I wouldn't even know how to search my doubt in google, so I'm going to try to explain myself as best as possible:
Right now I'm finishing a CMS with Symfony which does not stop refactoring(I always learn new things).
I have several services:
Very similar to Wordpress, I really like Wordpress.
But now I want to make that for example
and if for example I want to create a new Theme class that implements that interface to have it in any place of my application, the same for Shortcode and Nav. Actually the system I want to understand or do is very similar to Wordpress, for example in Wordpress in the functions.php file if you create and apply the add_shortcode function will be available anywhere. So my big doubt is that I have a chance to do it as organized and automatic as possible with Symfony.
Thanks!!!
UPDATE:
I just saw this post https://symfony.com/blog/ne... , which looks like it could do something similar to what I want, but I don't like the idea of every class I make or implement of for example my Interface Theme or Nav, I have to add it to services.yml, I don't think it's automated.
Any more ideas?
Hey Jose carlos C.
I'm not sure I'm following what you want to achieve. What you mean with "create an interface of each service or class". Have you read about compiler pass?
Cheers!
Hey, Yes I think that's the solution I'm gonna investigate what's going on.
Thanks
Finally I found it here https://symfonycasts.com/sc..., of course I didn't know the concept and I didn't know how to search. I'm going to try if I have any questions in linked video.
Thanks so much
Good find Jose carlos C.!
The tagging / compiler pass system is super advanced (not necessarily super hard, just not *that* commonly needed) but super power and cool. There is also a shortcut syntax if you want to automatically "inject" all classes with a certain "tag" into one of your services - https://symfony.com/blog/ne...
If you combine that with the "autoconfigure" feature, then you could make it so that ever class with a certain interface automatically gets passed to one of your services. Totally doable - the Symfony core does it all the time. Let us know if you have questions (maybe you already have and I haven't checked yet!).
Cheers!
thank you for this tip on perfromance using twig Extensions
Hey @Sidi-LEKHAIFA ,
We're happy to hear it was useful to you :)
Cheers!
Hello there!
If you want to test that your MardownHelper instantiates when calls
cached_markdownfilter but you are using the updated version of Lazy-Loaded Twig Extensions then putdie;into constructor of AppRuntime service!Enjoy :)
Hey Jayson,
Thank you for this tip ;) More information about it you can find in Symfony docs: https://symfony.com/doc/cur...
Cheers!
@2:30 ALT+Insert for Windows :)
Hey Ryan,
Thanks for sharing it with others Windows users ;)
Cheers!
is it worth the extra code? How much performance gain can we get from this trick? I though instatnces of services are very small things.
Hey Lijana Z.
That's a good question. It depends, if you have a dependency of a service which opens a DB connection or communicates to a email server, then, for sure you will want it to be lazy. I always do this trick, it's quite fast and simple to implement :)
Cheers!
yea, maybe on those cases, but I do not know, if I use dependencies which open DB connection, unless of those dependency depencies do this. Connectioin should be opened in constructor as I understand for this to be a problem but I do not do this.
Are there some symfony classes openening DB connections on instantiation which I should think about?
I believe an Entity Repository opens up a DB connection upon instantiation but I'm not totally sure
It's not works! I did all as shown. And got error:
Uncaught PHP Exception Twig_Error_Runtime: "An exception has been thrown during the rendering of a template ("The "App\Service\MarkdownHelper" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.")." at /Users/eugem/Developer/PHP/php-2HW08.mac/templates/article/show.html.twig line 31Help me please
Any update on that? It is happening to me. It is happening to me when die on the MarkdownHelper constructor. This helper is used as a filter. On the video, error does not appears, and title is shown...
I saw a question below. I was using wrong ContainerInterface. That's the correct one:
use Psr\Container\ContainerInterface;hey Beis
Awesome that you found what's wrong! If you will have some issues in feature stay in touch!
Cheers!
Hey Eugem
Check where you are fetching the service `MarkdownHelper` from the container and instead try using Dependency Injection or implement a ServiceContainer
Cheers!
Hello,
first of all, your website and its content is just mindblowing! almost to good to be true. thank you for that!
So my question is kinda trivial. Why is MarkdownHelper.php inside the Service-folder and not in the Helper-folder? Classes inside Helper should be an autowired Service aswell right?
Thanks in advance and keep on pushin'!
Hey AndTheGodsMadeLove
Thank you for your king words :)
About your question. You are correct, almost everything inside the "src/" directory is autowired and autoconfigured (if you didn't change your "services.yaml" file). The MarkdownHelper class lives inside the service directory only for highlighting the concept of services, but yes, it would fit better inside "Helper" directory
Cheers!
Sorry, it's me again. I can't understand the part of that video when we implement "getSubscribedServices" method from interface. I don't see point when we call that implemented method.
Second question. In constructor we type hint interface "ContainerInterface" not a class. In my knowledge (still not good enough) we use interfaces to defined head of methods and during interface implementation we have to define body of that implemented methods. So how come we can type hint interface and use not implemented method? Did I miss something from previous tutorials?
Regards
Hey Dominik!
Ha! It's no problem of course :)
Excellent question. And you're right: we NEVER call this method. Instead, when Symfony is building its container, it "notices" that we implement this interface and IT calls this method. It uses that information to create a "mini container" for us that it passes as the first argument to the method. This method basically provides configuration that is used by Symfony's core.
Another good question :). If you
dump($container)in the constructor, you will find that the object has aSymfony\Component\DependencyInjection\ServiceLocatorclass - which is a normal, concrete class (not an interface). So, you're 100% correct that you will always work with concrete classes. But, this ServiceLocator class DOES implement this ContainerInterface. So then, if we are passed a ServiceLocator object, you might wonder: why not use the ServiceLocator class in the type-hint for the argument instead of ContainerInterface? The answer is that, in general, using interfaces for your type-hints is a "better practice" that concrete classes. Even if you never need to do it, by using the interface type-hint, you (or Symfony) could, in the future, replace the ServiceLocator class with a totally different class. As long as that new class implements ContainerInterface, your code will still work. By using interface type-hints, we allow the "implementation" (i.e. specific class) to be replaceable with any other implementation of that interface.In fact, Symfony feels so strongly about promoting this best practice, the a lot of "autowiring" (the ability to type-hint an argument and have Symfony automatically pass you the correct service) ONLY works if you use the interface. For example, in this case, if you change the type-hint to ServiceLocator, it will not work - Symfony is more or less "forcing" you to use the interface to promote that best practice.
Let me know if this helps!
Cheers!
Now everything got sense. Thank you for brilliant and clear answer :). I regret now I didn't find this website when I started learning PHP :).
Regards.
Hi there!
I wrote "die;" at the top of the constructor and then I went to the article page. It resulted in a blank page (expected result); so, when I went to the 127.0.0.1:8000, it remains the blank page. What's wrong?
Cheers!
Hey Abelardo L.
I believe you are rendering an Article in your front page and because of that "die" statement your script stops being executed. Just remove the "die" statement :)
Cheers!
Same for me, writing die in the constructor results empty page on the homepage.
Hey Wazir Khan
Is there any other place where you are using the MarkdownHelper service?
Cheers!
Nope, checked the code again and again, earlier it was used in the show controller, removed that including the use statement from the ArticleController class. But still same result. The difference that I can see (comparing tutorial code and my code) is that I am using SF4.2.8 and the Interface used in the code is deprecated now. But it comes in another namespace
Symfony\Contracts\Service\ServiceSubscriberInterface, though, I tried with the deprecated interface as well, didn't work that too. my bad luck :)Hmm, that's weird. I believe I'll have to look at your code. Can you upload it to github or somewhere else?
Hi MolloKhan , thank you for the prompt support. Just pushed my code to github.
Here's the link: https://github.com/ahmadzai...
Ohh, so the
diestatement is inside the Twig extension class. That class is not being lazy loaded, what's been lazy loaded are all the services you define insidepublic static function getSubscribedServices(), in other words,MarkdownHelperThank you so much, I should have re-read/re-listened the scripts. Sorry for inconvenience.
I got the point. Working with Sf for some time, but on crazy way, now learning many new things that I never heard about. Once again thanks for such a fun tutorials (Y)
NP man! I'm glad to hear that you like our tutorials :)
Cheers!
I think a more elegant solution instead of following the service subscriber pattern is to use (as commented) the Lazy Service proxy:
https://symfony.com/doc/cur... and use standard Dependency Injection.
You don't need to follow my advice, who am I right?, but I think no one will discourage this:
https://www.php-fig.org/psr...
1.3 Recommended usage
Users SHOULD NOT pass a container into an object so that the object can retrieve its own dependencies.
This means the container is used as a Service Locator
which is a pattern that is generally discouraged.
Please refer to section 4 of the META document for more details.
Hey Qcho!
You make a great point! We are absolutely using a service locator pattern in this situation. In fact, the whole "service locator"/"service subscriber" feature we're using in Symfony was made possible by PSR-11 (the fact that the Container->get() method has a standard interface).
In general, yea, I think using a lazy service proxy is a simpler solution - you just use DI like every other places, so there's nothing extra to learn. But, there's one problem: you can currently only make your *own* services lazy - not core services. We could totally make MarkdownHelper lazy here. But, if we also needed the entity manager, we cannot make that lazy (well, technically we could with a compiler pass, but gets really complex). The service locator is a way around this. It's not as elegant as normal DI for sure. But, at least we're not passing in the *entire* container: we're passing in a "mini" container that only has the stuff we need in it. It's an unfortunate, necessary evil in some situations.
Cheers!
Does exist similar solution for symfony 2.8 ?
Hey bartek
Are you talking about the "autoconfigure" functionality? In that case, I'm fraid not. You have to define your Twig extension as a service and give it its tag
Cheers!
I meant Lazy Performance solution in twig.
Oh, in that case you can just fetch it from the container, that's how things was done in Symfony2
"Houston: no signs of life"
Start the conversation!