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

kenshin9's avatar

How to create binding based off Session value?

I'm trying to bind an object based on a variable in the session. I'm basically trying to implement the strategy design pattern by binding the concrete class based on that session variable. Originally, I was doing it in the AppServiceProvider, something like this (just an example):

    public function register()
    {
        $this->app->bind('App\Services\CompanyServiceAbstract', function($app)
        {
            $userType = Session::get('userType');

            switch ( $userType )
            {
                case UserType::MANAGER :
                        return $app->make('App\Services\CompanyServiceConcrete');
                case UserType::USER :
                        return $app->make('App\Services\AnotherCompanyServiceConcrete');
            }
        });
    }

But I know that the session isn't available there, as I've read Taylor's response somewhere about the absence of an HTTP request. So my question is, how should I accomplish something like this otherwise?

Also on that note for future reference, if I didn't need the session variable, is what I did above acceptable? The reason I used $app->make() was because the class would require dependencies in the constructor() method.

Any feedback would be greatly appreciated. Thanks!

0 likes
1 reply
vvvphpdev's avatar

really inside the register() function? it might be session service isn't loaded yet, can you put it inside boot() function instead?

Please or to participate in this conversation.