11.
Config Parameters
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.
33 Comments
`bind` is a killing-feature, thank you.
Meanwhile, are you planning to make a course for MultiLingual usage of Symfony and Doctrine. (not just talking about translations :)) It'd be lovely.
Thanks for great work.
Hey Yahya A. Erturan!
Yea, I love bind :). We ARE planning a tutorial about everything translations... but I would love to know what you're looking for the in that tutorial, so we can make sure we cover it - it's currently in the planning stages, so the timing is perfect.
Cheers!
I am thrilled that you are planning it already :) I am looking for a real life examples:
* redirect based on browser language or saving preferred language to a cookie. (For homepage of course)
* Slugs for each language. I think (but IMHO) hiding default language in url and displaying it in other languages is a good practice.
* to handle `article_meta` and `article_lang` tables (there is a bundle for that but I am eager to learn how it really works),
* to switch between languages,
* different language streams for frontend and backend,
* building sitemaps for each language
* etc.,
Sorry you hava asked :)
Hey Yahya,
Thanks for these topics! Well, most of them well be covered for sure. And I think I will reconsider others and try to include them too. Meanwhile, I'm not sure that I completely understand a few of them:
> to handle `article_meta` and `article_lang` tables (there is a bundle for that but I am eager to learn how it really works),
Just to be clear, what bundle are you talking about here?
> different language streams for frontend and backend
Can you explain a bit what "language streams" do you mean? For example, is it something like setting FR lang for admin panel but EN for the client's part? Because, I have never thought about it. Do you have a good use case where it may be really useful?
Cheers!
I'd be really happy to see such a tutorial :)
> to handle `article_meta` and `article_lang` tables....
KnpLabs/DoctrineBehaviors, A2Lix TranslationBundle as I saw in a tutorial after digging in Google :)
> different language streams for frontend and backend
For example, website's default language is English. Other available languages are German and French. As we are mostly working for international companies, in Admin panel (which is in English), our client is entering products in English. And asking their branch in France to enter details in French via Admin panel (which is still in English). We are handling it in our current system (which is highly modified version of CI 3 - and getting resemble to Symfony more day by day (thanks to your tutorials)) but at one point (after mastering in Doctrine and MultiLingual issues) we want to switch Symfony fully :)
Hey Yahya,
About the last, so after you filled in the EN information to your products, you're just looking for a way to fill in the same information but in FR and DE languages at the same time not switching language of the admin panel, right? So probably yeah, A2LixTranslationBundle I something you need, or I think it's also possible to implement manually with KnpLabsDoctrineBehaviors. Anyway, thanks for explanation! We'll consider these topics as well.
Cheers!
Admin Panel should have languages too :) So we have three language stream - 1: Main Data Stream (Adding pages to database via admin panel in several (if enabled) languages.) - 2: Frontend Stream (Displaying the records for selected languages in frontend) - 3: Backend Stream (Languages of Admin Panel - New Page / Nouvelle Page / Nuova Pagina / новая страница) - I have started to afraid of maybe it is too much real world for a tutorial :)
Hey Yahya,
Thanks for more detailed explanation! Haha, maybe too much. Well, I see the value to use one lang for admin panel but ability to fill in content into the DB in different langs, i.e. not changing language of admin panel each time you need to fill in content in a new lang. But what about separating langs for admin/fronted - I don't think it's worth it. If you use a lang on frontend - I think you'd 99% want to use the same lang in admin panel :)
Anyway, thanks for your ideas!
Cheers!
Hi there !
I am trying to set external parameters and I am trying to follow these instructions:
https://symfony.com/doc/3.2...
But I can't figure out what code must be written in the file which include_once refers to (in the above example /path/to/drupal/sites/default/settings.php).
Should I use a service to fetch the parameter and then pass it to parameters.php?
Do you have any concrete example to give me?
Sorry maybe my question sounds stupid for some of you, I am totally beginner with Symfony...
Just to be more specific: I would like to inject variables from the database into the config
Hey Simon L.
Just to be clear. You want to execute a query from a database to gather some parameters and then inject them into Symfony's container? If that's the case, you will have to code a script to do that query and use the service container as shown in the link you sent, and then, import that file
Cheers!
Just would like to add a question I had and the answer I found..
How to retrieve parameters values out there wether inside our controllers or our classes?
In Symfony 4 it's done using ParameterBagInterface. So we just add it there in the depencencies of the class.
Detailed explanation can be found here: https://stackoverflow.com/a...
Hey Ricardo M.
Thanks for sharing it! However it's not a good practice to pass whole ParameterBag inside your service, probably just in few cases when you really need a big amount of parameters. If not it's better to use autowiring. BTW it's also described in link you provided.
Cheers!
Hi Vladimir. Thanks for the reply.
You meant using `bind`, right? If so, I thought it was a little bit weird, specifying the value of every constructor variable with that name in the yaml file. I mean, it makes me creating weird variable names just to match those from config.
I was also wondering that Symfony would try to match them in every single constructor it loads, and that would be even slower.
Did I get this wrong?
Thanks for your attention one more time.
I'd like to say it depends. For example if you need one parameter in many services you can use
bind, but if you need a lot of different parameters in many services you can always mix autowiring with service definition for example:BTW there is a great course on Symfony 5 track: https://symfonycasts.com/screencast/symfony-fundamentals it has an awesome description of how autowiring working and how you can configure whatever you need ;)
Cheers!
Amazing, Vladimir.
Thank you a lot for this explanation. I learned about the autowiring in the course I'm taking, but didn't linked to what you said. Now it make sense.
Btw, I am currently using symfony 4.8 (LTS).
PS: I would love to take symfonycasts, but the price in USD currency broke my heart.
Hey Ricardo M.
We're sorry if it's expensive for you. We just think that it's a fair price for our job on them - we make them short but rich on information, and also give some jokes and nice animations to make learning not so boring.
But we do want to make it accessible to everyone, that's why we have some tutorials are completely free, and first few chapters of EVERY tutorial are literally free as well so you can try the course before buying. Also, the exact what we're saying in videos are described below each video in scripts, and it contains dynamic code blocks that you can expand. So you literally may code along with us for free.
Also, it depends on your learning strategy, but if our subscription prices are high for you - you can consider buying individual tutorials. Usually, they cost only about 12 USD. For example, this course you're currently on (Symfony 4 Fundamentals: Services, Config & Environments) costs only $10: https://symfonycasts.com/pr... - notice "No thanks, I just want to buy" below. But usually, with the monthly subscription you may learn more than 2 tutorials during the month, and so it might have more benefit for you. But it's up to you what to choose!
Cheers! Hope you enjoy learning!
Hi Vladimir. Please, don't get me wrong. It's not expensive. At least for those who lives there. :)
I'm an instructor myself. I try to price my courses comparing it to lunch prices in the regions of those who are buying it. Your subscription costs a lunch price in America, which is cheap. But costs 5 or 6 lunches in Brazil due to currency conversion. :)
And finally, the last option you gave me is the best one. I didn't see that at all. :)
I'm going to buy it for sure. :)
Thank you for your reply and support.
Hey Ricardo,
We are happy that you like our courses and especially found useful that small option :)
BTW we want to consider competitive pricing for different countries in the future. It's a really good idea, but we don't know exactly when it will be implemented, so no estimations yet (:
Cheers and stay safe!
Hello Symfonycast,
So I want to write configuration parameters for my Command class (this way I do not have to enter every time I run command)
I created in project/config/commands.yaml this file
And I make use of it in project/src/Command/ImportDataCommand.php like this:
But when I run command, I got error like this:
<blockquote>
C:\xampp\htdocs\project>php bin/console import:data
In DefinitionErrorExceptionPass.php line 54:
Cannot autowire service "App\Command\ImportDataCommand": argument "$communityNames" of method "__construct()" has no type-hint, you should configure its value explicitly.
</blockquote>
So can you see what I have done wrong or is it even a possible thing to do?
Thanks in advance!
Dung.
Hey Dung L. !
Hmm. This is a good question - because your config looks good to me! You are specifying the argument by name in commands.yaml, and so I would expect that it should be passed correctly to the service and not have this error. So, the problem is probably subtle - and I think I might see it. A few things:
A) In commands.yaml, you wrote
commands:. That is actuallyservices:, correct? I think you probably have this correct in your code but had a typo in the comment.B) Why did you create a
commands.ymlfile instead of putting this inservice.yaml? Here is what I think is happening:Let me know if this is the issue! I don't see a lot of point in separating things into multiple files like this. But if you do want to, I would "exclude" the Command directory from the auto-registration in services.yaml and then add code to commands.yaml to auto-register
src/Command. THEN, put your custom arguments code after that (so that your service is first auto-registered in commands.yaml, and THEN you override with your custom configuration).Cheers!
Hi Ryan,
- Does Symfony always loads [config-files].yaml first and auto-register all classes in src/ as services before it will do anything? I asked this because when I mimic this issue today, and I tried to run command "php bin/console cache:clear" and I get the same error above:
- php bin/console cache:clear command will not work until after I resolved this error.
I think my observation is correct, and all classes are essentially services in Symfony?
Thanks!
Dung.
Hey Dung L.!
Let me make sure I understand your question by giving you a full, long answer. Please tell me if I'm not understanding ;).
Yes, Symfony loads ALL the .yaml files (and auto-registers the classes in src/, because some code in services.yaml tells it to do that) in order to "build the container". This "build the container" process (sometimes called compilation) happens before Symfony starts handling a request and also before Symfony runs any console commands. So yes, ALL of the .yaml files are parsed, processeed, validated, etc before Symfony will do ANYTHING. This is actually a kill feature: it's not possible to have a typo on a service or be missing a command on a service and not realize it. In your example, if Symfony DID allow your code to continue, then you might not notice (until you tried to run that specific command) that the ImportDataCommand was broken. With the "compilation" step, nothing will work until everything is perfect.
You're close to being correct. A more accurate way to say it is this:
The code in services.yaml that auto-registers everything in src/ indeed does register everything in src/ (except for excluded directories) as a service. But, during the compilation phase, if a class in src/ is never used as a service (e.g. it's not autowired into a controller or passed as an argument to some other service), then it is removed from the container. It's a weird dance that produces a perfect result.
For example, suppose you have a
src/Model/CouponCodeclass. This is not a service, it's just some "model" class that you have decided to use - probably in some controller - like may be$code = new CouponCode('abc123')- and then you pass it into a template (I'm just making up this example). In this situation, this CouponCode class is NOT a service - it's a model class. In fact, if its first constructor argument is required (the "abc123" coupon code), then if Symfony things it's a service, it would FAIL autowiring and throw an error.Here's how this works inside Symfony during the compliation process:
a) Symfony registers everything in src/ a service, including CouponCode
b) It tries to autowire the "coupon code" constructor argument and fails. But it does not throw an exception, it "stores" this exception for later.
c) Near the end of the process, it notices that CouponCode was never used as a service - we never autowired it anywhere, for example. And so, Symfony removes it from the container. Because it removed it, the "autowiring error" is not thrown.
I hope that makes sense! The CouponCode is sort of "eligible" to be used as a service. But because you intend for it to be a model class, you never "use it" like a service - i.e. you never try to autowire it. And so, Symfony is smart enough to eventually make sure that it is NOT a service in the container.
Phew! Let me know if this helps!
Cheers!
Very good answer, I understand, its very clever behind the scene. Is this "eligible" but not registered as service for performance reason?
Hey Dung L.!
Excellent :).
> Is this "eligible" but not registered as service for performance reason?
The fact that Symfony "removes" any "unused" services from the container IS for performance, yes :). But in this situation, it's helpful for one other reason: if Symfony tries (and fails) to autowire a non-service class, when the service is later removed from the container, Symfony knows not to throw that "autowiring failed exception".
Cheers!
Hi weaverryan Thank you so much for your reply. You cleared it all for me and it works now. I misunderstood the material/course, I thought src/Command/* is not service just because it is a different directory than src/Service, I thought services must be under src/Service directory. Hence I created commands.yaml for it which results in the error.
So of course there was no point creating new .yaml config file :). Copying the same parameters and arguments from the mistaken commands.yaml to services.yaml bam it works ha ha. Now I know src/Command is also a service ( I should have known this because I learnt it some where on SymfonyCasts ). But thank you for your detail explanation I learnt even more with mistake/errors.
Cheers!
Woo! This sounds like a "win" all around - happy everything is making sense now! :)
Good Morning,
Sorry that I do not thing I understand Config Parameters topic. I simply want to write a config parameter in /config/services.yaml like this:
and use it in my service class src/Service/dataImport.php
but the $path variable does not get any value as expect instead it was an error. I hope you can help me?
error looks like this:
In JsonImport.php line 60:
Thank you for your support!
Dung.
Hey Dung L.
You have to inject all the parameters you need into your service class.
Cheers!
I got it working :) Symfony is addictive for programmer, it gets better with time, its cleaner and more powerful!
Thank you MolloKhan as usual.
Yeahhh it works !!! Awesome tutorial
HELP!
At the end of this tutorial, when I set APP_ENV=prod in my .env file ( to test the cache_adapter parameter), I get the following error when I refresh: "Something is broken. Please let us know what you were doing when this error occurred. We will fix it as soon as possible. Sorry for any inconvenience caused."
And my prod.log file has the following:
[2018-09-20 21:12:51] request.INFO: Matched route "article_show". {"route":"article_show","route_parameters":{"_route":"article_show","_controller":"App\\Controller\\ArticleController::show","slug":"why-asteroids-taste-like-bacons"},"request_uri":"http://127.0.0.1:8000/news/why-asteroids-taste-like-bacons","method":"GET"} []
[2018-09-20 21:12:51] request.CRITICAL: Uncaught PHP Exception RuntimeException: "Controller "App\Controller\ArticleController::show()" requires that you provide a value for the "$helper" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one." at /opt/lampp/htdocs/symfony/the_spacebar/vendor/symfony/http-kernel/Controller/ArgumentResolver.php line 78 {"exception":"[object] (RuntimeException(code: 0): Controller \"App\\Controller\\ArticleController::show()\" requires that you provide a value for the \"$helper\" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one. at /opt/lampp/htdocs/symfony/the_spacebar/vendor/symfony/http-kernel/Controller/ArgumentResolver.php:78)"} []
What have I done wrong?
Edit: OOoopss, I simply cleared my cache and it worked. I'll keep this here in case someone else does the same mistake.
Hey Ayman A.
I was about to tell you that you need to clear the cache everytime you make a change while working on prod environment.
Cheers!
"Houston: no signs of life"
Start the conversation!