Unresolvable dependency (Laravel 8)

Issue

using "jasny/sso" package, I’m getting following error:

Illuminate\Contracts\Container\BindingResolutionException
Unresolvable dependency resolving [Parameter #0 [ <required> callable $getBrokerInfo ]] in class Jasny\SSO\Server\Server

inside Jasny\SSO\Server\Server.php:

/**
 * Class constructor.
 *
 * @phpstan-param callable(string):?array{secret:string,domains:string[]} $getBrokerInfo
 * @phpstan-param CacheInterface                                          $cache
 */
public function __construct(callable $getBrokerInfo, CacheInterface $cache)
{
    $this->getBrokerInfo = \Closure::fromCallable($getBrokerInfo);
    $this->cache = $cache;

    $this->logger = new NullLogger();
    $this->session = new GlobalSession();
}

I’ve also tried:

php artisan route:clear
composer dump-autoload    
php artisan optimize:clear

could anyone point out the issue here?

Solution

As jasny/sso isn’t a laravel package, it should not be registered into the container without a specific set of instructions on how to instantiate it, based on it’s constructor.

In the register() method of AppServiceProvider add in the code below:

$this->app->bind(\Jasny\SSO\Server\Server::class, function($app) {
   $myCallable = function() {
       // do what you gotta do..
   };

   return new \Jasny\SSO\Server\Server($myCallable, $app->make(CacheInterface::class));
});

From there you can do the following anywhere in your application:

/** @var \Jasny\SSO\Server\Server $jasnyServer **/
$jasnyServer = app()->make(\Jasny\SSO\Server\Server::class);
$jasnyServer->changeTheWorld(true);

and it will automatically populate the constructor for you with the callable and CacheInterface we set in the bind (alternatively use $app->singleton() instead of bind, if you only ever require one instance of this class to exist throughout script execution).


Generally, anything you register into the container is subject to dependency injection by Laravel, therefore you cannot use an unknown type in your constructor as laravel has no way of knowing what the callable is, and will produce this error when that occurs.

Typically, if you had control over this, you would remove the callable from the constructor, and use a setter on your class instead.

private $callableFunc = null;

public function setCallable(callable $func) : void
{
    $this->callableFunc = $func;
}

Answered By – zanderwar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published