Dev
Dev

Reputation: 35

PHP - Routing two controllers with different actions to the same url

I have a route here with one controller linked with one action

'car/cars' => [
            'GET' => [
                'controller' => $CarController,
                'action' => 'cars'
            ],
          ]

This works perfectly fine for me until I add a second controller with a different action to the same route like so:

'car/cars' => [
            'GET' => [
                'controller' => $CarController,
                'action' => 'cars'
            ],
            'GET' => [
                'controller' => $ManufacturerController,
                'action' => 'list'
            ]
        ],

My issue is that the first action stops working and the second one starts working. Is there another way I can route two different actions to the car/cars url? I have tried the method below which gives me the same result

        'car/cars' => [
            'GET' => [
                'controller' => $CarController,
                'action' => 'cars'
            ],
        ],
        'car/cars' => [
            'GET' => [
                'controller' => $ManufacturerController,
                'action' => 'list'
            ],
        ],

Upvotes: 2

Views: 401

Answers (2)

Amr Aly
Amr Aly

Reputation: 3905

You can inject $manufactorerTable into your Car controller like so:

class Car {

  private $carsTable;
  private $manufactorerTable;

  public function __constructor($carsTable, $manufactorerTable) {
    $this->carsTable = $carsTable;
    $this->manufactorerTable = $manufactorerTable;
  }

  public function cars() {
    $cars = $this->carsTable->findAll();
    $manufactorer = $this->manufactorerTable->find('manufactorerid', 1)[0];

    return [
      ...
      'variables': [
        'cars' => $cars,
        'manufactorer' => $manufactorerTable
      ]
    ];
  }
}

and of course you will need only one route for this action which is:

'car/cars' => [
      'GET' => [
          'controller' => $CarController,
          'action' => 'cars'
      ],
 ]

Upvotes: 1

sietse85
sietse85

Reputation: 1506

 'car/cars' => [
        'GET' => [
            'controller' => $CarController,
            'action' => 'listCars' // new method to implement
        ],
    ],

Problem solved :)

Upvotes: 0

Related Questions