phpzend-framework-mvczend-framework3

Serializing objects to ZF3 MVC Response JSON


I have a Zend Framework 3 app. I added the ViewJsonStrategy to module.config.php. This lets the following endpoint return JSON:

public function helloAction() {
    return new JsonModel([
        'msg'=> 'Hello World!',
    ]);
}

However, I want to return objects

class HelloObjectResponse
{
    protected $message;

    public function getMessage() : string {
        return $this->message;
    }

    public function setMessage(string $message) : self  {
        $this->message = $message;
        return $this;
    }
}

public function helloObjectAction() {
    $obj = new HelloObjectResponse();
    $obj->setMessage('Hello World!');
    return new JsonModel($obj);
}

This gives me a Zend error message.

Zend\View\Model\ViewModel::setVariables: expects an array, or Traversable argument; received "Application\Model\HelloObjectResponse"

How do I make that object JSON easily in a way that zend will know to set the mime type and all that.


Solution

  • use Zend\View\Model\JsonModel;
    use Zend\Hydrator\Reflection;
    
    $obj = new HelloObjectResponse();
    $obj->setMessage('Hello World!');
    
    $hydrator = new Reflection;
    return new JsonModel($hydrator->extract($obj));