依赖注入Laravel

时间:2016-03-24 08:17:14

标签: php laravel dependency-injection laravel-5.1

我有一个门面类

use App\Http\Response 

class RUser
{
    public function signup(TokenGenerator $token_generator, $data)
    {
        $response = [];
        $access_token = $token_generator->generate(32);
        dd($access_token);
        $user = User::create($data);
        $response['user_id'] = $user->_id;
        $response[''];
    }
}

现在我的UserController我正在尝试使用RUser::signup()功能,如下所示

class UserController extends Controller
{
    public function store(Request $request)
    {
        $this->request = $request;
        $payload = json_decode($this->request->getContent());
        if($this->validateJson('user.create', $payload)) {
            $validator = Validator::make((array) $payload, User::$rules);
            if ($validator->fails()) {
                $messages = $validator->errors();
                return $this->sendResponse(false, $messages);
            }
            FUser::signup($payload);
            return $this->sendResponse(true, $response);
        }
    }
}

我认为Laravel会自动解决这些依赖关系,并且我不会明确地传递TokenGenerator的实例。但是我收到了以下错误。

Argument 1 passed to App\Http\Responses\RUser::signup() must be an instance of App\Utils\TokenGenerator, instance of stdClass given, called in 

2 个答案:

答案 0 :(得分:1)

默认情况下,Laravel仅在构造函数中为自定义类注入实例。控制器操作也将接收注入的实例。

因此,您的示例需要进行此类更改才能正常工作:

class RUser
{
    protected $token_generator;

    public function __construct(TokenGenerator $token_generator)
    {
        $this->token_generator = $token_generator;
    }

    public function signup($data)
    {
        $response = [];
        $access_token = $this->token_generator->generate(32);
        dd($access_token);
        $user = User::create($data);
        $response['user_id'] = $user->_id;
        $response[''];
    }
}

class UserController extends Controller
{
    public function store(Request $request, RUser $ruser)
    {
        $this->request = $request;
        $payload = json_decode($this->request->getContent());
        if($this->validateJson('user.create', $payload)) {
            $validator = Validator::make((array) $payload, User::$rules);
            if ($validator->fails()) {
                $messages = $validator->errors();
                return $this->sendResponse(false, $messages);
            }
            $ruser->signup($payload);
            return $this->sendResponse(true, $response);
        }
    }
}

要在自己实例化类时触发外部依赖注入,需要调用Illuminate \ Foundation \ Application实例的make()方法,如下所示:

$fooBar = $this->app->make('FooBar');

请参阅Laravel docs

答案 1 :(得分:0)

我认为你对Facades和Dependency Injection的使用感到困惑。 这里你应该遵循的是依赖注入据我所知,你可以直接在这里使用这个类,它可以毫无问题地工作TO have a clear idea of when to use facades and when to use dependency injection check this link