REST
Controllers are RESTful (Representational State Transfer) and can distinguish between different HTTP methods.
Restricting HTTP Methods
By using the name of the desired HTTP method as an additional prefix for a do method, you can restrict the HTTP methods via which this controller method can be invoked. For example, if a controller is called via GET with the command path /foo, it first looks for the method getDoFoo() and, if it does not exist, for doFoo().
class ExampleController extends ControllerAdapter {
public function getDoFoo() {
// GET
}
public function putDoFoo() {
// PUT
}
public function doFoo() {
// POST, DELETE
}
}
Assuming the command path /foo, in this example getDoFoo() can only be invoked via GET, putDoFoo() only via PUT and doFoo() only via POST and DELETE.
For all other controller methods, the allowed HTTP methods can be defined using the annotations n2n\web\http\annotation\AnnoGet, n2n\web\http\annotation\AnnoPut, n2n\web\http\annotation\AnnoPost and n2n\web\http\annotation\AnnoDelete. Via ControllerAdapter::getRequest()->getMethod() you can also query the HTTP method of the current request.
<?php
namespace atusch\controller;
use n2n\web\http\controller\ControllerAdapter;
use n2n\reflection\annotation\AnnoInit;
use n2n\web\http\annotation\AnnoGet;
use n2n\web\http\annotation\AnnoPut;
use n2n\web\http\Method;
class ExampleController extends ControllerAdapter {
private static function _annos(AnnoInit $ai) {
$ai->m('doFoo', new AnnoGet(), new AnnoPut());
}
public function doFoo($param) {
switch ($this->getRequest()->getMethod()) {
case Method::GET:
echo 'get: ' . $param;
break;
case Method::PUT:
echo 'put: ' . $param;
break;
}
}
}
Query Parameters
By annotating parameters of your controller method with the types below, you can have corresponding values from the URL or post query passed to you.
| Parameter type | Source | HTTP methods |
|---|---|---|
n2n\web\http\controller\ParamQuery | URL query | all |
n2n\web\http\controller\ParamGet | URL query | GET |
n2n\web\http\controller\ParamPut | URL query | PUT |
n2n\web\http\controller\ParamDelete | URL query | DELETE |
n2n\web\http\controller\ParamPost | post query | POST |
These parameter types can also be used to restrict the HTTP methods via which a controller method can be invoked. For example, if you define a mandatory parameter of type ParamGet for a controller method, it can only be invoked via GET requests.
Example 1
public function doFoo(ParamGet $param) {
// code
}
doFoo() can only be invoked via GET.
Example 2
public function doFoo(ParamGet $param = null) {
// code
}
doFoo() can be invoked via all HTTP methods. $param is only not null for GET requests with a matching URL query.
Example 3
public function doFoo(ParamQuery $param, ParamPost $param2) {
// code
}
doFoo() can only be invoked via POST. The request requires a parameter "param" in the URL query as well as a parameter "param2" in the post query.