【发布时间】: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,而是尝试像在代码的第一个版本中那样返回响应对象。