Search code examples
phplaravellaravel-4ioc-containercartalyst-sentry

how to Inject a Sentry 2 User Model into a controller - laravel 4


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'));
    }

}

Solution

  • 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