PHP - 将具有不同操作的两个控制器路由到同一个URL

时间:2018-04-12 22:59:52

标签: php routes

我这里有一条路线,其中一个控制器与一个动作相关联

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

这对我来说非常合适,直到我向同一路线添加第二个具有不同动作的控制器,如下所示:

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

我的问题是第一个动作停止工作,第二个动作开始工作。有没有其他方法可以将两个不同的操作路由到car/cars网址?我尝试过下面给出相同结果的方法

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

2 个答案:

答案 0 :(得分:1)

您可以将$manufactorerTable注入Car控制器,如下所示:

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
      ]
    ];
  }
}

当然,您只需要一条路线来执行此操作:

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

答案 1 :(得分:0)

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

问题解决了:))