0

I am trying to get it so any controller that extends base will have access to the User object created using the following method:

(This works just fine)

use My\Namespace\Repository;

class FooController extends \BaseController
{
    protected $user;
    protected $prop;

    public function __construct(UserRepository $user)
    {
        $this->user = $user;
        $this->prop = $this->user->getProp();
    }

    public function index()
    {
        return View::make('page')->with('userProp', $this->prop);
    }
}

However, I'm having trouble abstracting the creation of the user and getting the property out of FooController.php and putting it in BaseController.php so that it can be accessed by any controller that extends Base, like so:

class FooController extends \BaseController
{
    public function index()
    {
        return View::make('page')->with('userProp', $this->prop);
    }
}

Thanks.

2
  • 1
    Are you using the Auth class to handle security? If so, you should be able to access the current user virtually anywhere using: Auth::user(). Apr 12, 2014 at 23:12
  • Rubens: Yes, I tried to abstract out the bare minimum. I am not allowing all data to come back through, in the model getProp() limits the result to just that user. Apr 13, 2014 at 13:28

2 Answers 2

2

If you do like this it will work:

The user repository:

class UserRepository {

    public function getProp()
    {
        return 'user prop';
    }

}

The Base Controller

class BaseController extends Controller
{
    protected $user;
    protected $prop;

    public function __construct(UserRepository $user)
    {
        $this->user = $user;
        $this->prop = $this->user->getProp();
    }

}

The FooController extended from BaseController

class FooController extends BaseController
{
    public function index()
    {
        return $this->prop;
    }
}

And a route to test it:

Route::get('testuser', 'FooController@index');

To test, just add this code in the top of your routes.php file and hit that route.

0

The above example will not work as you have not called parent::__construct()

The example below breaks de-coupling but its the only way I've found without repeating the injection in all your sub classes

BaseController

protected $users;

$this->users = App::make('Repositories\Users\UsersRepositoryInterface');

FooController extends BaseController

return $this->users

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.