【问题标题】:How to stop continuing in beforefilter without continuing to the main controller?如何在不继续主控制器的情况下停止在 beforefilter 中继续?
【发布时间】:2016-04-15 07:46:54
【问题描述】:

我正在使用在 Cakephp 中呈现 json 格式的 API。 在AppController.php 我有:

public function beforeFilter() {
   $this->RequestHandler->renderAs($this, 'json');

   if($this->checkValid()) {
     $this->displayError();
   }
}
public function displayError() {
  $this->set([
     'result'     => "error",
     '_serialize' => 'result',
  ]);
  $this->response->send();
  $this->_stop();
}

但它不显示任何内容。但是,如果它正常运行而没有停止并显示:

$this->set([
 'result'     => "error",
 '_serialize' => 'result',
]);

显示良好。

【问题讨论】:

  • 我在某处读到,您需要在退出之前渲染视图以显示响应,但不确定..
  • beforeFilter 不会停止正在运行的控制器动作,你可以试试 $this->autoRender = false;这应该会停止您的控制器操作自动呈现视图。
  • 我明白了,谢谢@HelloSpeakman。有没有办法在不更改 URL 的情况下重定向到另一个控制器?

标签: php json api cakephp serialization


【解决方案1】:

我会考虑使用带有自定义 json 异常渲染器的异常。

if($this->checkValid()) {
  throw new BadRequestException('invalid request');
}

通过将其包含在您的 app/Config/bootstrap.php 中来添加自定义异常处理程序:

/**
 * Custom Exception Handler
 */
App::uses('AppExceptionHandler', 'Lib');

 Configure::write('Exception.handler', 'AppExceptionHandler::handleException');

然后在您的 app/Lib 文件夹中创建一个新的自定义异常处理程序,名为 AppExceptionHandler.php

此文件可能如下所示:

<?php

App::uses('CakeResponse', 'Network');
App::uses('Controller', 'Controller');

class AppExceptionHandler
{

    /*
     * @return json A json string of the error.
     */
    public static function handleException($exception)
    {
        $response = new CakeResponse();
        $response->statusCode($exception->getCode());
        $response->type('json');
        $response->send();
        echo json_encode(array(
            'status' => 'error',
            'code' => $exception->getCode(),
            'data' => array(
                'message' => $exception->getMessage()
            )
        ));
    }
}

【讨论】:

  • 谢谢!我会考虑这个。
猜你喜欢
  • 2019-09-16
  • 1970-01-01
  • 2018-01-29
  • 2018-08-22
  • 1970-01-01
  • 1970-01-01
  • 2022-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多