【问题标题】:Slim 3 no responseSlim 3 无反应
【发布时间】:2018-07-31 16:53:46
【问题描述】:

所以这是我第一次拥有的:

$app->get('/object/{id:[0-9]+}', function ($request, $response, $args) {    
    $id = (int)$args['id'];
    $this->logger->addInfo('Get Object', array('id' => $id));
    $mapper = new ObjectMapper($this->db);
    $object = $mapper->getObjectById($id);
    return $response->withJson((array)$object);
});

它运行良好,并将整个 DB 对象输出为一个不错的 JSON 字符串。

现在我在 MVC 的基础上重新组织了一切,剩下的就是:

$app->get('/object/{id:[0-9]+}', ObjectController::class . ':show')->setName('object.show');

它也有效,但我没有得到任何输出。如果我在 DB 对象之前放置了一个 var_dump,但是我如何再次从中获取 JSON 字符串?

控制器来了

<?php
namespace Mycomp\Controllers\Object;

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Interop\Container\ContainerInterface;
use Mycomp\Models\Object;

class ObjectController
{
    protected $validator;
    protected $db;
    protected $auth;
    protected $fractal;

    public function __construct(ContainerInterface $container)
    {
        $this->db = $container->get('db');
        $this->logger = $container->get('logger');
    }

    public function show(Request $request, Response $response, array $args)
    {
        $id = (int)$args['id'];

        $this->logger->addInfo('Get Object', array('id' => $id));

        $object = new Object($this->db);
        return $object->getObjectById($id);
    }
}

【问题讨论】:

  • 能否包含您的 ObjectController 类的代码
  • 我觉得我们需要更多关于这里发生的事情的信息ObjectController::class . ':show'
  • 应该是这个:':show' 是这个:'::show'?
  • 添加了控制器
  • 不要在show 方法中返回$object,而是尝试像在代码的第一个版本中那样返回响应对象。

标签: php rest slim slim-3


【解决方案1】:

正如尼玛在评论中所说,你需要返回Response对象

public function show(Request $request, Response $response, array $args)
    ...  
    return $response->withJson($object->getObjectById($id));
}

【讨论】:

    【解决方案2】:

    为了让 Slim 向客户端发送 HTTP 响应,路由回调必须返回一些 Slim 可以理解的数据。这种类型的数据,according to Slim documentation 是一个 PSR 7 Response 对象。

    这很重要,因为路由回调返回的内容不一定会完全按原样发送给客户端。中间件可能会使用它在将响应发送给客户端之前对其进行解析。

    $response 对象,由 Slim 注入到您的路由回调中,用于此目的。 Slim 还提供了一些辅助方法,例如“withJson”,以生成具有正确 HTTP 标头的正确 (PSR 7) JSON 响应。

    正如我在评论中所说,您需要返回响应对象

    public function show(Request $request, Response $response, array $args)
        // Prepare what you want to return and
        // Encode output data as JSON and return a proper response using withJson method  
        return $response->withJson($object->getObjectById($id));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 2021-10-05
      • 2018-06-18
      • 2017-06-18
      • 1970-01-01
      • 2016-05-17
      相关资源
      最近更新 更多