Score:-2

Set variable for drupal 9 website

sx flag

I need to get the hostname and then define a variable which is going to be used in all controllers of the website. I am able to call the code in controller as follows:

$host = \Drupal::request()->getHost();
\Drupal::logger('host')->notice($host);

switch($host)
{
  case 'A';
    $var = "A";
    break;
  case 'B';
    $var = "B";
    break;
  case 'C';
    $var = "C";
    break;
  case 'D';
    $var = "D";
    break;
  default;
    $var = "";
    break;
}

But instead of defining it in all Controllers, I want to define it at a very beginning, then create a global variable(eg. $var) which I would be able to call in all controllers. I need to know which hook or event would help me in this scenario.

ru flag
Create a service with a function returning your variable: https://www.drupal.org/docs/drupal-apis/services-and-dependency-injection/services-and-dependency-injection-in-drupal-8#s-defining-services-by-fully-qualified-name-of-php-namespace
Score:0
cn flag

I want to define it at a very beginning, then create a global variable(eg. $var) which I would be able to call in all controllers.

Defining a global variable for this use case is bad practice, and should be avoided.

Instead, you should create a custom service which injects the request_stack service, and provides a method to get your host variable based on that.

Then inject your custom service into each of your controllers, and make use of that method to get the variable.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.