簡體   English   中英

Slim 3無反應

[英]Slim 3 no response

這就是我的初衷:

$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);
});

它運行良好,並且將整個數據庫對象作為一個不錯的JSON字符串輸出。

現在我在MVC的基礎上重新整理了所有內容,剩下的就是:

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

它也可以,但是我沒有任何輸出。 如果我在數據庫對象之前放置了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);
    }
}

正如Nima在評論中所說,您需要返回Response對象

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

為了使Slim向客戶端發送HTTP響應,路由回調必須返回Slim可以理解的一些數據。 根據Slim文檔 ,該類型的數據是PSR 7 Response對象。

這很重要,因為路由回調返回的內容不一定會完全按原樣發送給客戶端。 中間件可能會使用它在將響應發送給客戶端之前先獲取響應。

Slim注入到路由回調中的$response對象用於此目的。 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));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM