Reputation: 494
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.
Upvotes: 0
Views: 2799
Reputation: 154
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
Upvotes: 0
Reputation: 87769
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.
Upvotes: 2