Passing JSON data to action as class (explicit declaration)

5 years ago

mishak
Member | 100
+
0
-

I got this idea after watching introduction video for Knockout.js library where was shown how easy it is to get JSON data in ASP.

Basically this is the idea:

<?php
class Response {
    /** @var Record[] */
    public $records;
}
class Records {
    /** @var string */
    public $name;
    /** @var string */
    public $email;
    /* ... */
}

class JsonPresenter extends \Nette\Application\UI\Presenter {
    public function actionSave(Response $response)
    {
        foreach ($response->records as $record)
        {
            /* ... */
        }
    }
}
?>

Conditions:

  • JSON is checked against classes definitions and if fails appropriate http error is returned
  • to action is passed only valid class (never null)

Benefits:

  • reduced amount of edge cases
  • no JSON parsing (handled transparently) – less overhead in actual action code
  • simpler testing
  • explicit data contract

Does this seem as a good idea?

Last edited by mishak (2013-04-24 17:20)