我有一个这样的课程:
class PostValidator
{
public function __construct(Validator $validator, $data)
{
$this->validator = $validator;
$this->data = $data;
}
}
我阅读了关于IoC自动解析的Laravel文档,它给出了一个例子:
class FooBar {
public function __construct(Baz $baz)
{
$this->baz = $baz;
}
}
$fooBar = App::make('FooBar');
是否可以在没有App::make
(带闭包)的情况下使用App::bind
来实例化上面的类,同时传递参数$data
?
答案 0 :(得分:3)
不,你做不到。
这个想法是你只将依赖项传递给构造函数,显然data
不是一个。 Validator使用数据,但不依赖于数据。
而是使用setter作为数据。
class PostValidator
{
public function __construct(Validator $validator)
{
$this->validator = $validator;
}
public function setData($data)
{
$this->data = $data;
}
}
并且只需明确地调用它:
$validator = App::make('PostValidator');
$validator->setData($data);
// or in the controller, which is what you're doing most likely
public function __construct(PostValidator $validator)
{
$this->validaotr = $validator;
}
public function update($id)
{
$data = Input::only([ input that you need ]);
$this->validator->setData($data);
// run the validation
...
}
编辑:根据评论,这是第二个参数$parameters
的作用:
// Foo class with Eloquent Models as dependencies
public function __construct(User $user, Category $category, Post $post)
{
$this->user = $user;
$this->category = $category;
$this->post = $post;
}
然后IoC容器将依赖关系解析为新实例化的模型:
$foo = App::make('Foo');
$foo->user; // exists = false
$foo->category; // exists = false
$foo->post; // exists = false
但如果你愿意,你可以这样做:
$user = User::first();
$cat = Category::find($someId);
$foo = App::make('Foo', ['category' => $cat, 'user' => $user]);
$foo->user; // exists = true, instance you provided
$foo->category; // exists = true, instance you provided
$foo->post; // exists = false, newly instantiated like before