How Can I define global CONST variables in my app symfony ? What are the good practices define global variables in symfony? Mayby Should I create interface and use DI ?
-
1Depending on your need, you may be able to put them under parameters in your config.yml. Can you provide a more specific example of how you would use these vars?Don't Panic– Don't Panic2017-11-18 18:26:59 +00:00Commented Nov 18, 2017 at 18:26
-
1symfony.com/doc/current/best_practices/…Cerad– Cerad2017-11-18 18:28:18 +00:00Commented Nov 18, 2017 at 18:28
2 Answers
You should add your variables into app/config/config.yml;
# app/config/config.yml
parameters:
myVariable: 10
And you can use it;
$this->getParameter('myVariable');
2 Comments
If it's a constant, it wont change, in other words: it's not a parameter. Therefore, has no sense and it's not optimal to put it in Symfony configuration files.
In my opinion, the best practice is to define it in the class you are using:
namespace App\Entity;
class Foo {
const MyConst = 'A value';
/* ...... */
If you need it in different places, you can create a class to define there your application constants:
namespace App\Classes;
class Constants {
const MyConst = 'Hello world!';
/* ...... */
}
Then, you can use this class wherever you need it:
namespace App\Controller\Frontend;
use App\Classes\Constants;
class FooController extends AbstractController
{
/* ...... */
public function bar()
{
echo Constants::MyConst;
}
}
All of this is based on the fact that its value does not depend on the environment, if is not the case, you should use .env file.