Dunsin Olubobokun
Dunsin Olubobokun

Reputation: 902

Can we have two or more classes in a Laravel controller

Considering Interface Segregation Principle, which is one among the most “talked about” principles of Object Oriented Programming - SOLID principles, I was wondering if it were possible to have two different classes in a single Laravel controller? For example:

  <?php

    namespace ...;

    use App\Http\Controllers\Controller;

    interface VehicleInterface
    {
      public function ...
    }

    class CarController extends Controller implements VehicleInterface
    {
       ...
    }

    class ElectricCar implements VehicleInterface
    { 
       ...
    }

Upvotes: 3

Views: 2373

Answers (2)

Ulrich Thomas Gabor
Ulrich Thomas Gabor

Reputation: 6654

This question has at least two problems:

  1. I do not think that ElectricCar and CarController should share the same interface. The ElectricCar models a car, possibly with methods like accelerateTo(120mph) whereas the CarController maybe has methods like accelerateCarTo(Car5, 120mph). They are also used with a different meaning: The ElectricCar models one single car, whereas the CarController manages access to a single or multiple cars, which is also called from a abstract construct modeling an application flow.

  2. The interface segregation principle does not speak about classes, so the question is ill-formed in the first place. The interface segregation principle says that one interface(!) specifying multiple use cases should be broken up into multiple interfaces(!) called role interfaces, each fulfilling exactly one use case. For example, an interface modeling an ATM with methods like deposit() and withdraw() should be split up into two interfaces each only fulfilling one of these functions. The goal is that a dependent entity must only use and see the parts it really requires.

Upvotes: 3

William Randokun
William Randokun

Reputation: 153

Technically you can have multiple classes in the same file.

With Laravel (or any framework), not really, if you want to use its autoloader, as classname = filename is the convention.

Also, a controller is what handles requests. You can load as many instances of your different classes inside a controller function. But defining other classes inside the controller file is not what you're supposed to do, at all.

Upvotes: 6

Related Questions