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

DaemonKeen's avatar

Singleton, class / instance injection

Hey, I would like to create ONLY one instance of a class and use it several times in my UserController. I set up a singleton in AppServiceProvider (hopefully correctly) like:

$this->app->singleton('skautis', function ($app) {
            $config = new Config(env('SKAUTIS_APP_ID'), true, true, true);
            $sessionAdapter = new \Skautis\SessionAdapter\SessionAdapter();
            $webServiceFactory = new \Skautis\Wsdl\WebServiceFactory();
            $wsdlManager = new WsdlManager($webServiceFactory, $config);
            $user = new SkautisUser($wsdlManager, $sessionAdapter);
            return new Skautis($wsdlManager, $user);
        });

and then I access the instance in UserController by app('skautis').

In this callback I set user login data:

public function loginSkautisCallback(Request $request, )
    {
        try {
            app('skautis')->setLoginData($request->all());
        } catch (\Throwable $th) {
            toast()->warning('Přihlášení se nezdařilo.')->pushOnNextPage();
            return redirect('/');
        }
}


//dd(app('skautis')); will correct user data:

Skautis\Skautis {#598 ▼ // app\Http\Controllers\UserController.php:286
  -wsdlManager: Skautis\Wsdl\WsdlManager {#593 ▶}
  -user: Skautis\User {#597 ▼
    -wsdlManager: Skautis\Wsdl\WsdlManager {#593 ▶}
    -session: Skautis\SessionAdapter\SessionAdapter {#586 ▶}
    #loginData: array:4 [▼
      "ID_Login" => "3615c778-7443-602u-9r23-0d004a70q738"
      "ID_Role" => 10632
      "ID_Unit" => 37567
      "LOGOUT_Date" => DateTime @1673272203 {#600 ▶}
    ]
  }
  -log: null

but I can't access it in another function:

public function importSkautis()
    {
        dd(app('skautis'));
    }

//returns empty object:

Skautis\Skautis {#1360 ▼ // app\Http\Controllers\UserController.php:309
  -wsdlManager: Skautis\Wsdl\WsdlManager {#608 ▶}
  -user: Skautis\User {#1362 ▼
    -wsdlManager: Skautis\Wsdl\WsdlManager {#608 ▶}
    -session: Skautis\SessionAdapter\SessionAdapter {#1427 ▼
      #session: & []
    }
    #loginData: []
  }
  -log: null
}

My point is to set user data in one function and work with the user (the instance) in another function.

0 likes
4 replies
Sinnbeck's avatar

Do not use env() outside of config files. Using the config class does not help. Move it to an actual file

Sinnbeck's avatar

@DaemonKeen this goes inside a config file. Check any file in /config to see how it works

env('SKAUTIS_APP_ID')
Sinnbeck's avatar

Why would two different controller methods be called in one request? I assume it's actually two seperate requests. Laravel or php forgets all state at the end of the request (unless using octane). So store whatever data you need between requests in the session, database or redis

Please or to participate in this conversation.