1

我正在开发一个 API,因为我(大部分)具有相同的功能,所以我创建了一个抽象类以在我的控制器上进行扩展。

我的抽象类看起来像: http: //laravel.io/bin/23Bzj

在控制器中我将使用模型和响应构造的位置(稍后可能会将响应移动到 ApiController 构造函数)。

class EventController extends ApiController
{

  public function __construct(Event $model, ResponseRepository $response)
  {
     $this->model = $model;
     $this->response = $response;
  }
}

但问题是:我将如何使用Request我的 ApiController 中的特定类在验证方法中使用/什么是最佳实践。

我可以使用普通Request类,但在方法之前我不会进行任何验证。

当我在我的时候,EventController我将能够使用UpdateEventRequest等等CreateEventRequest

4

1 回答 1

1

据我所知,如果您以任何方法在控制器中使用

public function edit(UpdateEventRequest $req) {
  // any code
}

在启动// any code部分验证之前将完成。

你可以尝试做什么:

  1. update将抽象类中的方法更改为受保护
  2. 将此方法的签名从更改public function update(Request $request, $id)public function update($request, $id)- 我不知道这一步是否必要
  3. 例如realUpdate,使用以下代码创建新方法:

    public function realUpdate(UpdateEventRequest $req, $id) {
       parent::update($req, $id);
    }
    

我不确定第 2 步,因为如果您Request在抽象类中使用,我不知道 Laravel 是否会尝试运行任何验证。它也有可能再次运行此验证UpdateEventRequest- 你应该试一试,我还没有测试过。

基本上你会有类似这样的代码:

<?php

class X
{

}

class Y extends X
{

}


abstract class ApiController
{

    protected function update(X $x, $id)
    {
        echo "I have " . get_class($x) . ' and id ' . $id;
    }
}


class Controller extends ApiController
{

    public function realUpdate(Y $y, $id)
    {
        parent::update($y, $id);
    }
}

$c = new Controller();
$c->realUpdate(new Y, 2);

并且 Laravel 应该根据UpdateEventRequest.

您不能在子类中为此方法使用相同的名称,因为您会收到警告:

严格标准:Controller::update() 的声明应与 ... 第 31 行中的 ApiController::update(X $x, $id) 兼容

但是它仍然可以工作,但我假设您不想收到任何警告。

于 2014-10-04T13:36:10.683 回答