Laravel __construct() - 不注入?

I'l*_*ack 1 php laravel laravel-5.3

我收到错误:

GitHubApp::__construct() must be an instance of App\Project\Repositories\GitProviderRepository
Run Code Online (Sandbox Code Playgroud)

我认为 Laravel 做了某种魔法,所以__construct()我不必将它注入new GitHubApp();

  use App\Project\Repositories\GitProviderRepository;

    class GitHubApp
    {
        private $gitProviderRepository;

        public function __construct(GitProviderRepository $gitProviderRepository)
        {
            $this->gitProviderRepository = $gitProviderRepository;
        }
    }
Run Code Online (Sandbox Code Playgroud)

在其他班级:

return new GitHubApp();
Run Code Online (Sandbox Code Playgroud)

Ris*_*ana 6

当调用 时new GithubApp(),你依靠自己构建GithubApp实例,Laravel 不负责构建该实例。

你必须让 Laravel 为你解决依赖关系。有多种方法可以实现这一目标:

使用App门面:

App::make(GithubApp::class);
Run Code Online (Sandbox Code Playgroud)

使用app()辅助方法:

app(GithubApp::class);
Run Code Online (Sandbox Code Playgroud)

或者使用resolve()辅助方法:

resolve(GithubApp::class);
Run Code Online (Sandbox Code Playgroud)

在幕后,您的类类型及其依赖项将由该类Illuminate\Container\Container( 的父类Application)解析并实例化。具体通过make()build()方法。

希望这有帮助!:)