How to process %kernel.project_dir% from a .env variable? - php

I added this to my .env:
PHOTOS_DIR=%kernel.project_dir%/var/photos
Of course, when I try to retrieve the value of $_ENV['PHOTOS_DIR'], I get the raw string %kernel.project_dir%/var/photos.
But how can I get the value processed by the Symfony config processor, e.g. /my/project/var/photos?
EDIT:
I'm aware that it is simply possible to add this in services.yaml:
parameters:
photos_dir: '%kernel.project_dir%/var/photos'
But I would like to keep important config data in the .env file.

In order to expand %kernel.project_dir%, use %env(resolve:...) in parameters, e.g.:
parameters:
photos_dir: '%env(resolve:PHOTOS_DIR)%'

Your dotenv does not process the symfony yaml processor parameters.
Delete the %kernel.project_dir% from .env file and in your .yaml you need to bind a parameter like this:
photos_absolute_path: '%kernel.project_dir%%env(PHOTOS_DIR)%'
After that you can get the parameter from your container by the name of photos_absolute_path and it will point to the correct location

Using symfony parameters in .env-files is correct. Symfony will automatically resolve them.
After container will be compiled, you can get the real value if you bind it to a parameter.
.env
PHOTOS_DIR=%kernel.project_dir%/var/photos
services.yaml:
parameters:
photos_dir: '%env(PHOTOS_DIR)%'
Somewhere in your application:
$container->getParameter('photos_dir');

Related

What could possibly cause getenv to fail when the variable is present in .env file?

I have an .env file containing SOME_IP=127.0.0.1:8080. In a Laravel controller for a certain request I call $foo = getenv('SOME_IP');. About 90% of the time it works fine, I get the string and proceed. But the other 10% of times, getenv returns false, even though the variable is clearly in the .env file. What could be causing this?
Alternatively, Laravel's env returns null.
Observed with vlucas/phpdotenv v2.6.4.
Maybe it's because of caching the config.
It is better to load your env variable in a config file and then retrieve it from the config.
For example you can create a file with the name 'ips' in config directory like this:
<?php
return ['someIp' => env('SOME_IP')];
and then use
$foo = config('ips.someIp')

How define some PHP constant in the Symfony configuration?

this is my first post, so i will try to be clear
So i need to define some constants in the Symfony configuration (in a .yaml file, i guess)
I know i could define them throw public const MY_CONST but that is not what I want.
I guess this is what i need (the second part, i am not using Abstract controller as i am not in a controller)
https://symfony.com/doc/current/configuration.html#accessing-configuration-parameters
But I just can't get it to work. Could anyone help me, by giving me an exemple, or maybe an other way to do ?
Thanks guys.
The parameters you described can be used in the configuration defined as eg;
parameters:
the_answer: 42
You can then use these values in further configuration things (see below for example). Or if you want to handle these values in a controller you can (not recommended anymore) use $this->getParameter('the_answer') to get the value.
Binding arguments (recommended):
This approach wil bind values which you can then get (auto-magically injected) in a controller function/service by referencing the argument.
The values can range from simple scalar values to services, .env variables, php constants and all of the other things the configuration can parse.
# config/services.yaml
services:
_defaults:
bind:
string $helloWorld: 'Hello world!' # simple string
int $theAnswer: '%the_answer%' # reference an already defined parameter.
string $apiKey: '%env(REMOTE_API)%' # env variable.
Then these get injected in a service/controller function when we do something like:
public function hello(string $apiKey, int $theAnswer, string $helloWorld) {
// do things with $apiKey, $theAnswer and $helloWorld
}
More details and examples can be found in the symfony docs https://symfony.com/doc/current/service_container.html#binding-arguments-by-name-or-type
Inject into service (alternative)
You can also directly inject it into the defined service using arguments.
# config/services.yaml
services:
# explicitly configure the service
App\Updates\SiteUpdateManager:
arguments:
$adminEmail: 'manager#example.com'

What is best way to create variable in environment file?

In laravel I need to create variable in env file. According to documentation and some relevant threads (got after googling) I need to do add variables in .env file
I have tried following
SANDBOX_PAYPAL_CLIENT_ID=7I3D9
SANDBOX_PAYPAL_CLIENT_SECRET=S2E4C5R6E7T
I am confused that after adding here variable I just need to call then into controller or I need to setup again in somewhere ./config/ directory? What is best practice, can someone guide me about that. I would like to appreciate. Thank you
You should put env variables in .env file, but make sure to only use env() calls in configuration files (the ones under /config) to retrieve their values.
Keep in mind that if you cache the configuration (php artisan config:cache) any env() will return null as Laravel will no longer load .env files.
That's also stated in to the documentation
You can get .env variables using the env() helper function.
Most packages get these values in their conf file to group the configurations.
You can then use the config() helper function to get the value.
However you implement this is up to you.
It depends on how you want to use them. Maybe create a file with name ConfigVariables.php declare all variables of env there.
1) You can have all of them at one place. Centralized control of all env variables at one place.
2) Take care of null checks etc, if config doesn't exit, pass some default value
3) This will help you to have one standard being used for all
4) If you use env directly in the code, you will have to check and take care of the null values (in case if there is no variable in the config)
Just to add a point here, Strings with spaces could be an issue if you do not use ""
You can test it:
Email_Sender_Name=Danyal Sandeelo
echo it as: echo env("Email_Sender_Name");
Email_Sender_Name="Danyal Sandeelo"
echo it as: echo env("Email_Sender_Name");
You can read this one: Laravel 5.2 not reading env file

Symfony 3 own global configuration file

How i can create and use own global config with keys/values in symfony?
I was try set keys/values in parameters.yml under parameters line which been in this file after instalation and get it like $pageTitle = $this->getParameter('myKey'); and it works but i want own whole config file with structure for ex. $this->getParameter('myParameters.myKey') so:
I was created new file:
#app/config/myConfig.yml
myParameters:
myKey: myValue
In config.yml i added:
#app/config/config.yml
imports:
- { resource: myConfig.yml }
and in controller:
$pageTitle = $this->getParameter('myKey');
And i have exception:
FileLoaderLoadException in FileLoader.php line 118: There is no extension able to load the configuration for "inyconfig" (in....
EDIT
This example works but you must do one little change - myParameters change to parameters and everything is work like a charm.
You have to do a dependency injection e.g. BundleNameDependencieInjection related of your bundle and then create Configuration class that provide configure external dependence and/or external configurations
Have a look there http://symfony.com/doc/current/bundles/configuration.html#processing-the-configs-array
In parameters you can create some scalar or array variables that can be called in some circumstances in your case you may create an array with some range like that :
parameters:
# scalar
one.two.three: something
# array
oneBis:
twoBis:
threeBis: somethingBis
Use parameters instead of myParameters.
So, put in app/config/myConfig.yml:
parameters:
myKey: myValue

Passing parameters to my custom logger in symfony

I am having some troubles using the logger service in Symfony2. I find it quite confusing.
I am trying to use a Rotating File Handler. To this handler zou can pass 3 paramenters: the filename of the log, maxFiles that the log can divide itself and log level.
I want to pass this parameters from the controller, since I load that data in runtime from a .ini configuration file, but I am not sure how to do it.
How could I do this?
Try the following in your controller:
add a use statement: use Monolog\Handler\RotatingFileHandler;
use it like this: $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);

Categories