Zend Expressive API не возвращает содержимое объектов - PullRequest
0 голосов
/ 15 марта 2019

Я создаю небольшой API, в основном для целей обучения, но я мог бы реализовать его в проекте, над которым я работаю. До сих пор я установил приложение Zend Expressive Skeleton и настроил свои модели и объекты. Я могу запросить базу данных и получить результаты, но когда я возвращаю результаты в виде ответа JSON, я вижу только список пустых массивов для каждого результата. Я хотел бы иметь возможность возвращать реальные объекты, которые возвращаются из базы данных, а не преобразовывать их в массивы.

HomePageHandler.php

<?php

declare(strict_types=1);

namespace App\Handler;

use App\Entity\Product;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Expressive\Router;
use Zend\Expressive\Template\TemplateRendererInterface;
use App\Model\ProductModel;

class HomePageHandler implements RequestHandlerInterface
{
    /** @var string */
    private $containerName;

    /** @var Router\RouterInterface */
    private $router;

    /** @var null|TemplateRendererInterface */
    private $template;

    private $productModel;

    public function __construct(
        string $containerName,
        Router\RouterInterface $router,
        ?TemplateRendererInterface $template = null,
        ProductModel $productModel
    ) {
        $this->containerName = $containerName;
        $this->router        = $router;
        $this->template      = $template;
        $this->productModel  = $productModel;
    }

    public function handle(ServerRequestInterface $request) : ResponseInterface
    {
        $data = $this->productModel->fetchAllProducts();

        return new JsonResponse([$data]);

        //return new HtmlResponse($this->template->render('app::home-page', $data));
    }
}

Я ожидаю, что ответ JSON вернется со списком из 18 объектов «Продукт». Мои результаты выглядят как.

[[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]]

Дайте мне знать, есть ли другой код, который вы хотели бы увидеть. Заранее спасибо!

Отредактировано с кодом Product.php

<?php
/**
 * Created by PhpStorm.
 * User: Brock H. Caldwell
 * Date: 3/14/2019
 * Time: 4:04 PM
 */

namespace App\Entity;

class Product
{
    protected $id;
    protected $picture;
    protected $shortDescription;
    protected $longDescription;
    protected $dimensions;
    protected $price;
    protected $sold;

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getPicture()
    {
        return $this->picture;
    }

    /**
     * @param mixed $picture
     */
    public function setPicture($picture)
    {
        $this->picture = $picture;
    }

    /**
     * @return mixed
     */
    public function getShortDescription()
    {
        return $this->shortDescription;
    }

    /**
     * @param mixed $shortDescription
     */
    public function setShortDescription($shortDescription)
    {
        $this->shortDescription = $shortDescription;
    }

    /**
     * @return mixed
     */
    public function getLongDescription()
    {
        return $this->longDescription;
    }

    /**
     * @param mixed $longDescription
     */
    public function setLongDescription($longDescription)
    {
        $this->longDescription = $longDescription;
    }

    /**
     * @return mixed
     */
    public function getDimensions()
    {
        return $this->dimensions;
    }

    /**
     * @param mixed $dimensions
     */
    public function setDimensions($dimensions)
    {
        $this->dimensions = $dimensions;
    }

    /**
     * @return mixed
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * @param mixed $price
     */
    public function setPrice($price)
    {
        $this->price = $price;
    }

    /**
     * @return mixed
     */
    public function getSold()
    {
        return $this->sold;
    }

    /**
     * @param mixed $sold
     */
    public function setSold($sold)
    {
        $this->sold = $sold;
    }

    public function exchangeArray($data)
    {
        $this->id = (!empty($data['id'])) ? $data['id'] : null;
        $this->picture = (!empty($data['picture'])) ? $data['picture'] : null;
        $this->shortDescription = (!empty($data['shortDescription'])) ? $data['shortDescription'] : null;
        $this->longDescription = (!empty($data['longDescription'])) ? $data['longDescription'] : null;
        $this->dimensions = (!empty($data['dimensions'])) ? $data['dimensions'] : null;
        $this->price = (!empty($data['price'])) ? $data['price'] : null;
        $this->sold = (!empty($data['sold'])) ? $data['sold'] : null;
    }
}

1 Ответ

1 голос
/ 15 марта 2019

Вам нужно либо сделать свойства общедоступными, либо реализовать интерфейс JsonSerializable в вашей сущности Product.Все его свойства защищены, что хорошо, но это означает, что они не отображаются, когда объект закодирован в JSON.

Вот несколько кратких примеров:

class Example1 {  protected $a = 1;  }

class Example2 {  public $b = 2; }

class Example3 implements JsonSerializable {
    protected $c = 3;
    public function jsonSerialize() {
        return ['c' => $this->c];
    }
}

echo json_encode([new Example1, new Example2, new Example3]);

Результат:

[{},{"b":2},{"c":3}]

Если вы решите реализовать JsonSerializable, то точно, как вы это делаете, зависит только от вас, но вам просто нужен метод jsonSerialize(), который возвращает нужные вам свойства в результате JSON в форматедоступно для json_encode (объект с общедоступными свойствами или массив).

...