never_easy
never_easy

Reputation: 21

How to handle repositories/interfaces with controller inheritance in Laravel 4?

I'm having an issue with using repositories/interfaces in my controllers. My app is using Laravel 4.

My current controller inheritance tree is:

 +- BaseController
     +- FrontendController
         +- ProductController

In the FrontendController I am getting/setting some things to use across the board in my controllers, so I have set the interfaces in the constructor like so:

class FrontendController extends BaseController
{
    /**
     * Constructor
     */
    public function __construct(SystemRepositoryInterface $system,
                                BrandRepositoryInterface $brands,
                                CategoryRepositoryInterface $categories)

However, this now means I'm having to send through the interfaces (again) in all of my child controllers like so:

class ProductController extends FrontendController
{
    /**
     * Constructor
     */
    public function __construct(SystemRepositoryInterface $system,
                                BrandRepositoryInterface $brands,
                                CategoryRepositoryInterface $categories,
                                ProductRepositoryInterface $products)
    {
        parent::__construct($system, $brands, $categories);

I'm new to this level/area of PHP but it feels wrong, am I missing something obvious?

Upvotes: 1

Views: 1228

Answers (1)

Jan P.
Jan P.

Reputation: 3297

No, you are not wrong. PHP does not support method overloading like other languages. So you have to rewrite the constructor of your FrontendController every time (Bro tip: A good IDE should help you a lot here ;>). Laravel resolves all of the controllers constructor dependencies via its IoC-Container. Just add

App::bind('SystemRepositoryInterface', function() {
    return new EloquentSystemRepository();
});

for every repository in one of the bootstrap files of your application. And the framework will do the injection for you.

Upvotes: 1

Related Questions