【问题标题】:How would I pass in the request class to my abstract class?我如何将请求类传递给我的抽象类?
【发布时间】:2014-11-28 18:39:37
【问题描述】:

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

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

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

class EventController extends ApiController
{

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

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

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

当我在我的EventController 中时,我将能够使用UpdateEventRequestCreateEventRequest 等等。

【问题讨论】:

    标签: php design-patterns laravel laravel-5


    【解决方案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) 兼容

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      相关资源
      最近更新 更多