08.
Creating Services!
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
Whoops, an error! Please, try again later.
55 Comments
./bin/console debug:autowiring
In DefinitionErrorExceptionPass.php line 54:
Cannot autowire service "App\Service\MarkdownHelper": argument "$isDebug" o
f method "__construct()" is type-hinted "bool", you should configure its value explicitly.
any idea ?
Hey Ad F. ,
The error make sense, Symfony unable to guess what exactly value to pass for $isDebug parameter, so just specify it obviously:
Cheers!
I did exactly that and I still see the error. Every reference online gives the same answer. It almost feels like I hit a bug or something.
Hey Anna,
Hm, looks like it helped Anna Filina :/ What Symfony version do you use? Could you clear the cache and try again?
Cheers!
Is there any benefit of somehow constructing with a singleton pattern so the services are statics?
Hey Richard
When you use Dependency injection in Symfony, it's like all your services were a Singleton. The container will give you always the same object (during the same request, of course)
Cheers!
Hello SymfonyCasts,
With your help thus far I can now even dive in deeper with Symfony 4. Thanks!
My story is. The way I collect data and store data in dbase for my application is not thru an input form, but from a web host json page like this tutorial (https://symfonycasts.com/sc....
I use file_get_contents() to read it, then in Controller/ I write (class ImportController extends AbstractController) to process the data and store data into the mysql database (I write entity classes for each db table and using Entity->setProperty() to persist data to database as normal standard Symfony routines). So when I want to import data to database I have to hit a url such as https://localhost:8000/import-data/community.json this will call to the route/import-data controller and everything works perfectly! Database and relations populated.
Now, I realized this can be a problem such as php execution timeout, security vulnerability and etc ... SO here is my question: Can I move this controller class with many functions in it to a Service or ConsoleCommand etc .. so that I can execute it internally and re-use it?
I have tried to moved this controller class ImportController to both Services and Command (console commands) but failed with errors such as:
Thank you so much for your guidance, please point me to a direction.
Dung.
Hey Dung L.
That's an interesting use case :)
What you can do is to extract all the logic for importing the data from the URL and just use such service from a Controller or a Command. You can inject your service by using normal dependency injection. I believe you are relying on the auto-config and auto-register functionality of Symfony4
Cheers!
Hello MolloKhan,
I am not sure you understood my question, so here is the entire class code, can you please take a closer look and guide me again since I did not understand what to do.
https://uofc-my.sharepoint....
the import call is from a url exactly like this:
https://localhost:8000/import-data/community2.json
I can also post the Repository/Services/Command/Entity and Templates if needed.
*** I am on the auto-config and auto-register functionality of Symfony4
Thanks so much!
Dung.
Hi Dung L.,
So if I did understand your suggestion hence I tried to transform this controller class to a service class and it looks like this within Service folder.
https://uofc-my.sharepoint....
Now that the service above is created I use it in Command, in command I wrote it like this (please ignore codes from SymfonyCasts' tutorial) in Command folder. And just focus on method $jsonImport->importEstateDataAction.
https://uofc-my.sharepoint....
And finally I test it in Command line as described in this image and resulted in error as in image.
https://uofc-my.sharepoint....
I would like to ask you:
Changing to this implementation in order to import data from Json file to database is proper way to import json data to database? Can you see how to fix this error? Is there a better way to achieve what I want to do. If you can please point me to the right direction I very much appreciate!
Dung.
Hey Dung L.
Oh, I see what you did. You need to be aware of when you are working out of a controller you don't have access to any of its methods, or access to the container. What you need to do is to inject the EntityManager into your service, and replace all calls to
$this->getDoctrine()E.G.
Cheers!
Hi MolloKhan ,
how do I instantiate this service class in console/command class? true are not the right args
Thanks!
D.
Hi Dung L.
- so i changed service class to - see link
https://uofc-my.sharepoint....
- then initialized this service class in console/command class - see link
https://uofc-my.sharepoint....
- finally ran this command resulted in error - see link
https://uofc-my.sharepoint....
I know that I am confused and not knowing how to use the service class, where to make call, but I am not sure how to overcome it. Thanks for any help!
Dung.
Uhm, may be I can not call/use it within console commands?
I found this doc https://symfony.com/doc/cur... will try it out :)
updated code for ImportDataCommand.php in Command dir:
https://uofc-my.sharepoint....
new error but better error I believe:
https://uofc-my.sharepoint....
I think i am closer
yes, got it. The problem is exact what we see in the error message :), great job Symfony! So in Service's JsonImport class, I changed the constructor method type-hint to class interface instead of class type as seen below and it works :) (replaced EntityManager type to EntityManagerInterface type)
Thank you Dung L. for your pointer. KnpUniversity you are awesome :)
Dung.
Hey Dung L.
I'm so glad to hear that you could fix your problem. Nice job man and thanks for the kind words :)
Hi,$cache and $markdown are passed when instantiating the MarkdownHelper, but imagine that $cache and $markdown need to be configured, how is it done?
Hey Benoit L.
If you need to configure a service because the autowiring feature can't do it for you (like injecting a string value), there are a couple of ways to do it. I'll point you to the documentation, so you can get a better understanding of what's going on but if you have more doubts let us know :)
https://symfony.com/doc/cur...
Cheers!
Autowiring is super awesome feature, it shouold have been existing earlier. I think in Laravel 4 when I was injecting, I did not need setting configs for each class, and when I went to symfony for me it was weird to have so much manual work.
Hey Coder,
Thank you for your feedback about autowiring! Agree, it's a great feature!
Cheers!
For some reason, i always need to restart my server to see the change after i edited and saved my file. Or after waiting a minute and then hitting refresh, only then i can see the changes. Doing a cache:clear, then hitting refresh crashes my server with the following error:
- [ERROR] Server terminated unexpectedly.
I'm in dev environment. Can someone please help?
Hey Saruulbuyan,
That's weird :) Can you tell me on which Symfony version are you and how are you starting your web server? Also double check that you are running on dev environment by running
bin/console- at the top of the output you will see the environmentCheers!
Hi Diego,
Sorry for not answering quickly.
php bin/console server:runbin/console, I get this:"Symfony 4.2.4 (env: dev, debug: true)"
In later tutorials I downloaded the source codes and I didn't have problem like this. Until tutorial "Symfony 4 Forms: Build, Render & Conquer!". I'm back to this issue. But in this tutorial("Symfony 4 Forms") I'm using Symfony version 4.1.6.
Interesting... I'm not sure what's causing it but at least you can try deleting your vendor directory and run
composer install && composer updateIf it's still failing, please reply to my following questions:
On what OS are you?
What's your PHP version?
Did you modify
public/index.phpfile?Double check file permissions under
var/folderI tried deleting vendor dir and ran the following commands:
composer installcomposer updateStill the same... Answering your questions:
public/indexfileHey Saruulbuyan O.
Try to run
php -S localhost:8000 -t public/and look if it fails again. If it will have same issues, than we will need to check php extensions and configuration. First try to disable all non-standard dlls for examplexdebug,apcu,opcacheand than repeat your test. Better to disable one by one to guess what exactly cause the issue.Cheers!
Hi Vladimir,
I tried running
php -S localhost:8000 -t public/. Still the same.As for extensions i've only installed acpu, but never used in symfony. But I still tried disabling acpu extension but no change...
I tried it in chrome, firefox, opera and even edge browsers... I still always have to restart the server to see the changes on my browser. It's not a major issue, but still annoying. Thanks anyways for the help guys :)
Hm this is interesting. What about
php_opchache.dll? It's installed in php be default. Have you installed php manually? Oh and could you please re-install vendorsvendor/directorycomposer install(now without update just install)And last question, could you please share complete
php -voutput?It works!!!! I disabled
php_opcache.dllAnd now Its working normally. I can see my changes immediately. Thank you sir! :) In case you need myphp -vouptput:`PHP 7.1.27 (cli) (built: Mar 6 2019 20:51:04) ( ZTS MSVC14 (Visual C++ 2015) x64 )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies
Hi, Why When I do bin/console debug:autowiring | grep "cache" -B 1, there is 2 alias to cache.app; result:
--
Psr\Cache\CacheItemPoolInterface
alias to cache.app
--
Symfony\Component\Cache\Adapter\AdapterInterface
alias to cache.app
---
And Why did u shoose the second One ?
Hey Med,
Actually, it's not too much important, you can chose any of those two. But CacheItemPoolInterface is more low-level, i.e. AdapterInterface "extends" CacheItemPoolInterface. There are technical reasons behind of it, most probably AdapterInterface has been existed before CacheItemPoolInterface and I think it might be that AdapterInterface will be deprecated in the future, or maybe not, I'm not sure. But since you use Symfony - it makes sense to typehint with AdapterInterface I think.
Cheers!
Hi everyone,
I have created a new class src\Service\EmailSender and I created a public function called sendEmail.
Then, I run ./bin/console debug:autowiring but it doesn't appear in the output list.
What's wrong when I created this class as service?
Brs.
Hey Abelardo L.!
Don't worry - it should work :). There was a change in Symfony 4.2 - debug:autowiring no longer shows YOUR services - it only shows third-party services. We will soon be adding a note to this tutorial to make sure people know - it's confusing if you're not expecting it.
Cheers!
Actually, let me be a bit more accurate. Check out my other comment below: https://symfonycasts.com/sc...
Cheers!
Thanks so much for your quick reply!
Happy days!
So bin/console debug:autowiring doesn't show my custom service (neither does --show-private) but I can still autowire the service just fine as shown in the tutorial. Is this some kind of change from when this video was made?
Hey Aaron,
Do you see your service if you run
bin/console debug:container?Yes, it's there.
Hey Aaron!
No worries - you are FINE. We need to add a note to this tutorial for a change in Symfony 4.2. Starting in Symfony 4.2, debug:autowiring ONLY shows 3rd-party autowireable services - it does not show your OWN services that are autowirable (the idea is that you already know about this stuff). Sorry if that confused you - we're going to add it to our list to add a note!
Cheers!
Actually, let me be a bit more accurate. It now only shows service "aliases", and by default, the services that you create are not aliases, so they don't show up. If that doesn't make sense to you, don't worry :). You can also pass a
--alloption to see everything.I get following error:
Cannot resolve argument $markdownHelper of "App\Controller\ArticleController::show()": Cannot autowire service "App\Service\MarkdownHelper": argument "$cache" of method "__construct()" has type "App\Service\AdapterInterface" but this class was not found.
In the logging:
CRITICAL
17:31:11
request Uncaught PHP Exception Symfony\Component\DependencyInjection\Exception\RuntimeException: "Cannot resolve argument $markdownHelper of "App\Controller\ArticleController::show()": Cannot autowire service "App\Service\MarkdownHelper": argument "$cache" of method "__construct()" has type "App\Service\AdapterInterface" but this class was not found." at /Users/sarah/Sites/the_spacebar/var/cache/dev/ContainerKfYMbmx/getMarkdownHelperService.php line 9
Any idea?
Does it have to do with this when I do ./bin/console debug:autowiring
Symfony\Component\Cache\Adapter\AdapterInterface
alias to cache.app
Hey Sarah V.!
Ah! This is a tricky one! Ok, look at this part of the error message closely:
The clue is that, for some reason, PHP thinks that you have type-hinted your argument with
App\Service\AdapterInterface. But of course, you intended this to beSymfony\Component\Cache\Adapter\AdapterInterface.The problem is that you're missing the
usestatement for theAdapterInterfaceclass at the top of your MarkdownHelper service. Because of this, PHP assumes that the AdapterInterface must live in the current namespace (App\Service) not the one you want.Add the use statement and this will all work instantly! Missing use statements are one of the most annoying, but common issues. You'll quickly learn to spot them and fix them :).
Cheers!
Hi everyone,
Why does this message appear after to write "php bin/console debug:autowiring"?
In ContainerBuilder.php line 1011:
You have requested a non-existent Service "session.storage.native".
What's wrong?
Best regards.
Hey Abelardo L.
That's odd, are you requesting that service in your "services.yaml" file?
Can you tell me which Symfony version are you using?
If you haven't done anything interesting, probably is just an unexpected error, try clearing the cache and/or reinstalling your vendors
Cheers!
Hi @Diego Aguiar,
"services.yaml" file? Where is it explained during the video?
Symfony 4.
You meant to delete the vendor dir and execute composer install ...or what another command should I use to reinstall my vendors?
Best regards.
Hey Abelardo,
Did you download the code for this course? I just tried to download the code and run "bin/console debug:autowiring" and I do not see this error. Yes, Diego means deleting vendor/ dir and re-installing dependencies, i.e:
$ rm -rf vendor/
$ composer install
I don't see we're talking about "session.storage.native" service in this course, or tell me if I'm wrong. So probably this error does not relates to some changes we're doing in this screencast.
So try to clear the cache before running "bin/console debug:autowiring". Does it helps? Or you still see this error?
And yeah, we understand that you're on Symfony 4, but could you tell us more precise version, like v4.0.14 that we're using in this course. You can see it in the Symfony web debug toolbar in the right bottom cornet.
Cheers!
Anybody here?
Hey Abelardo!
Yeah, we're here! Sorry for the delay. I answered your previous comment, hope this helps you, if not - let us know.
Cheers!
"Houston: no signs of life"
Start the conversation!