如何在Laravel服务提供程序中传递构造函数依赖项



我正在服务提供者中注册我的社交身份验证服务,我的接口的实现需要其构造函数中的参数。

如何通过服务提供商传递?这是我的代码,但它在语法上不正确。

namespace AppProviders;
use IlluminateSupportServiceProvider;
use App;
use AppUser;
use IlluminateContractsAuthGuard;
use LaravelSocialiteContractsFactory as Socialite;
class SocialAuthenticationServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        App::bind('AppRepositoriesSocialAuthenticationInterface', function () {
            return new AppRepositoriesSocialAuthentication(Socialite $socialite, Guard $auth, User $user);
        });
    }
}

正确的方法是使用 new 关键字,而不是将依赖项分配给变量。并确保您的类已导入(例如,使用 Guard)位于类的顶部。

public function register()
{
    App::bind('AppRepositoriesSocialAuthenticationInterface', function () {
        return new AppRepositoriesSocialAuthentication(new Socialite, new Guard, new User);
    });
}

最新更新