通过外部 class 修改 Slim 3 中的响应 Object

Modify Response Object in Slim 3 via external class

我的 slim 应用程序有问题,我想发送 json 响应,但使用自定义 headers。我的代码如下:

index.php

require 'vendor/autoload.php';
require 'app/config.php';
require 'app/libs/api.cs.php';

$app = new Slim\App(    
    [
        "settings" => $config,
        "apics" => function() { return new APIHelper(); } //This is a class that contain a "helper" for api responses
    ]
  );

require 'app/dependences.php';
require 'app/middleware.php';
require 'app/loader.php';
require 'app/routes.php';

// Run app
$app->run();

app/libs/api.cs.php ("helper")

<?php
class APIHelper
{
    public function sendResponse($response, $status='success' ,$code = 200, $message = "", $data = null)
    {
      $arrResponse = array();  
      $arrResponse['status'] = $status;
      $arrResponse['code'] = $code;
      $arrResponse['message'] = $message;  
      $arrResponse['data'] = $data;
       return $response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization, AeroTkn')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        ->withHeader('Content-Type','application/json')
        ->withHeader('X-Powered-By','My API Server')
        ->withJson($arrResponse,$code);
    }
}

我的路线文件(app/routes.php)

$app->group('/foo', function () {
  $this->get('', function ($req, $res, $args) {
    return $this->apics->sendResponse($res, 'success' ,200, "Foo API Index By Get", null);
});

  $this->post('', function ($req, $res, $args) {
    try{
        $oBody = $req->getParsedBody();
        return $this->apics->sendResponse($res, 'success' ,200, "Foo API POST Response", $oBody);        
      }
      catch(\Exception $ex){
        return $this->apics->sendResponse($res, 'error' ,500, "Process Error", array('error' => $ex->getMessage()));
    }   
  });
});

当我尝试 运行 我的应用请求 body 时,结果如下: Headers:

connection →Keep-Alive
content-type →text/html
date →Wed, 30 Aug 2017 02:22:56 GMT
keep-alive →timeout=2, max=500
server →Apache
transfer-encoding →chunked

Body(returns 作为简单文本而不是 json 编码)

{"status":"success","code":200,"message":"Foo API POST Response","data":{"one":"1", "two":"2"}}

我试图将此 class 作为中间件,但我对这些主题有些困惑。

你能帮我告诉我这些方法是好是坏。

感谢大家,我希望得到你们的回答!美好的一天

使用中间件是您问题的理想答案

只需将此函数添加到您的中间件文件中即可

 $app->add(function ($req, $res, $next) {
        $response = $next($req, $res);
        return $response
        ->withHeader('Access-Control-Allow-Origin', 'http://mysite')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
         ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
         ->withHeader('Content-Type','application/json');
        ->withHeader('X-Powered-By','My API Server');
    });

我发现"error"是一个幼儿园问题哈哈哈,我已经从网络服务器上下载了我所有的代码在我的机器上测试,我得到了相同的结果,但我发现我所有的文件都有开头有奇怪的字符,所以我将文件重新保存为utf-8,问题就解决了。让人头疼的小细节!感谢尼卡和拉米。 Ramy:解决方案非常好,现在代码更有条理,我采用这种做法。大家好。