Question

Is it possible to bind an instance into a method parameter of a resourceful controller in laravel 4?

Is this even a good idea? If I have an object that I need for just one method, is it worth it to include it as a constructor parameter?

app/routes.php

Route::Resource('track', 'TrackController');

app/controller/TrackController.php

class TrackController extends BaseController {
  public function __construct(/Foo/Bar p1, /Foo/Baz p2)
  {
    // All these bindings seem to work
  }

  public function show($id, /Foo/Xyz $xyz)
  {
    // This binding doesn't work, even though the exact same binding
    // in the constructor will work.
  }
}
Was it helpful?

Solution

Automatic Resolution works only for constructors:

When a type is not bound in the container, it will use PHP's Reflection facilities to inspect the class and read the constructor's type-hints. Using this information, the container can automatically build an instance of the class.

The best you could do in this case might be:

class TrackController extends BaseController {

    public function __construct(/Foo/Bar p1, /Foo/Baz p2, /Foo/Xyz $xyz)
    {
        $this->xyz = $xyz;
    }

    public function show($id)
    {
        echo $this->xyz->property;
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top