0

In a "common" application, the controller forwards the data in a ViewModel object to the view. There it can be prepaired for the output, e.g.

 `id`                       -> `/foo/bar/` . `$course->id`                  -> `link`
 `firstname` and `lastname` -> `$course->name`                              -> `name`
 `date`                     -> `AgeHelper(`$course->date`)` . ' years old.' -> `age`
 etc. ...

Now I'm developing a RESTful application and missing this view level. It's currently working like this:

Controller

public function get($id)
{
    $course = $this->getCourseTable()->findOnceByID($id)->current();
    $viewModel = $this->acceptableViewModelSelector($this->acceptCriteria);
    $viewModel->setVariables(array('data' => array(
        'id'             => $course->id,
        'created_at'     => $course->created_at,
        'details'        => $course->details,
    )));
    return $viewModel;
}

But it's only sufficient for shallow data structures. Where should the data be processed / prepaired for the ViewModel?

  • Controller? No, not in the controller.
  • Model? Not in the model table or mapper class.
  • View? would be nice, but there is no views.

So, where?

Thanks

automatix
  • 14,018
  • 26
  • 105
  • 230

1 Answers1

2

JSON is mostly used to transfer raw data in comparison to rendering HTML where it make sense to have this extra "presentation" layer in form of view scripts. Looking at your code it looks like you are using table gateway pattern to retrieve entities. Thus I believe you've got these options here:

  • Return JsonModel and pass only raw data from your row object and let JS/other application to format them as needed
  • Return JsonModel and pass data pre-formatted in your controller using some 'helper' TableGateway or RowGateway methods or you might want to consider implementing some controller plugins to do this.
  • Return JsonModel and pass formatted data using methods like TableGateway::toJson($row) or RowGateway::toJson() which you implement.
  • Return ViewModel and pass your entities to view script as you would with ordinary HTML templates. You can format the output as you need there using view helpers. Then use Zend\View\Helper\Json view helper to set 'application/json' response with your data --- NOTE: it looks like Json helper does not work as it's documented so until it's fixed or you replace it with your own implementation this is not really an option for you :)
Matus Zeman
  • 81
  • 1
  • 2