xdim222
xdim222

Reputation: 463

Laravel automatic resolution with parameters

I have a class like this:

class PostValidator 
{
     public function __construct(Validator $validator, $data) 
     {
          $this->validator = $validator;
          $this->data = $data;
     }
}

I read Laravel doc about IoC automatic resolution, it gives an example:

class FooBar {

    public function __construct(Baz $baz)
    {
        $this->baz = $baz;
    }

}

$fooBar = App::make('FooBar');

Is it possible to use App::make only without App::bind (with closure) to instantiate my class above which also passing parameter $data?

Upvotes: 3

Views: 7542

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81177

No, you can't do that.

The idea is that you pass only the dependencies to the constructor, and obviously data is not one. Validator works with the data, but does not depend on the data.

Instead use setter for the data.

class PostValidator 
{
     public function __construct(Validator $validator)
     {
          $this->validator = $validator;
     }

     public function setData($data)
     {
          $this->data = $data;
     }
}

and simply call it explicitly:

$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
  ...
}

edit: as per comment, this is what 2nd argument $parameters does:

// 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;
}

then IoC container will resolve the dependencies as newly instantiated models:

$foo = App::make('Foo');
$foo->user; // exists = false
$foo->category; // exists = false
$foo->post; // exists = false

but you can do this if you want:

$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

Upvotes: 8

Related Questions