Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

andyandy's avatar

Global variable across Controllers, Views, Services ... computed just once

I have variable $account_value that is used in Controller, View, random Classes, AppServiceProvider. Its value has to be calculated/retrieved from database.

What is the best approach to calculate its value "globally" just once. And then use it in Controller, View, Classes, AppServiceProvider ... ? Calculate just once on each request.

0 likes
6 replies
andyandy's avatar

@Sinnbeck

That's my current solution. But I run into a issue, where singleton called inside AppServiceProvider will create its own instance.

// Conversion class

class Conversion {
  public class __construct(){
     Log::debug('i was called');
  }
}

If app(Conversion::class)->get()['id'] used only in Controllers/Views log will contain only one message.

But if also used in AppServiceProvider it will run twice!

//AppServiceProvider.php

    public function boot()
    {

        $this->app->singleton(Conversion::class, function () {
            return new Conversion();
        });

         // if I add this line Log will contain "i was called" twice
        view()->share('app_currency_id', app(Conversion::class)->get()['id']);
Sinnbeck's avatar

@andyandy you can try with a view composer as it uses a function and should be called after bootstrapping

Snapey's avatar

or write a helper that gets it from session

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Or you can use a static property on a helper class (kinda what singletons are under the hood)

Or put it in cache using the array driver (if it only should be there for 1 request)

Please or to participate in this conversation.