1

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 ?

2
  • 1
    Depending 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? Commented Nov 18, 2017 at 18:26
  • 1
    symfony.com/doc/current/best_practices/… Commented Nov 18, 2017 at 18:28

2 Answers 2

3

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');
Sign up to request clarification or add additional context in comments.

2 Comments

Parameters are not constants, they are variables, hence they can have variable content, not constant.
@PaulAllsopp That's right. Actually, PHP 8 provides "Enums" for a better solution. Constant variables aren't recommended for modern applications. However, it's a trade-off.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.