0

How do you inject a Sentry 2 User model into a laravel 4 controller using IoC?

for example i would like the following

class myController extends BaseController {

    /**
     * creates a list of MyModel Models
     *
     * @return View
     */
    public function getIndex( User $user )
    {
        // fetch models
        $models = MyModel::all();

        // Show the page
        return View::make('my-views.the-view', compact('models', 'user'));
    }

}
AndrewMcLagan
  • 13,459
  • 23
  • 91
  • 158

1 Answers1

1

This is how I like to do it:

class myController extends BaseController {

    $protected $user

    /**
     * creates a list of MyModel Models
     *
     * @return View
     */

    function __construct(User $user){
        parent::__construct();
        $this->user = $user;
    }

    public function getIndex()
    {
        // fetch models
        $models = MyModel::all();

        // Show the page
        return View::make('my-views.the-view', compact('models', 'user'));
    }

}

You can also do it in the method, but... well, give this a good read, too: http://fabien.potencier.org/article/11/what-is-dependency-injection

Ryan
  • 5,959
  • 2
  • 25
  • 24
  • This is great.. although i have realised that this returns the actual Sentry User model not the Sentry Provider Model so we would need to do the following: `App::instance( 'User', Sentry::GetUser() );` – AndrewMcLagan Oct 18 '13 at 09:42
  • ALSO... to save having `compact('models', 'user')` in each view call. We could instead place `View::share('user', $user);` in the base controller constructor. – AndrewMcLagan Oct 18 '13 at 09:45
  • also you may be able to help me answer this question... as you seem in the IoC know how :-) http://stackoverflow.com/questions/19445615/route-model-binding-and-soft-deletes-laravel-4 – AndrewMcLagan Oct 18 '13 at 09:50
  • 1
    You got it - You do App::instance('foo', $foo); to "store" it, and then App::make('foo') to get it back out. In addition to View::share(), check out http://laravel.com/docs/responses#view-composers – Ryan Oct 18 '13 at 10:01