I'll-Be-Back I'll-Be-Back - 24 days ago 10
PHP Question

Laravel __construct() - without injecting?

I am getting error:

GitHubApp::__construct() must be an instance of App\Project\Repositories\GitProviderRepository


I thought Laravel does some kind of magic when it come to
__construct()
so i don't have to inject it into
new GitHubApp();
?

use App\Project\Repositories\GitProviderRepository;

class GitHubApp
{
private $gitProviderRepository;

public function __construct(GitProviderRepository $gitProviderRepository)
{
$this->gitProviderRepository = $gitProviderRepository;
}
}


In other class:

return new GitHubApp();

Answer

When calling new GithubApp(), you relied on yourself to build the GithubApp instance, Laravel does not responsible for building that instance.

You have to let Laravel resolve the dependencies for you. There are numbers of way to achieve this:

Using App facade:

App::make(GithubApp::class);

Using app() helper method:

app(GithubApp::class);

Or using the resolve() helper method:

resolve(GithubApp::class);

Behind the scene, your class type and its dependencies will be resolved and instantiated by the Illuminate\Container\Container class (the parent class of Application). Specifically by the make() and build() methods.

Hope this help! :)