1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* The nested resource controller can help you to avoid some boilerplate in nested resources in you rest api. |
5
|
|
|
* |
6
|
|
|
* If you have a resource `user` and the endpoint `/users` then a nested resource could be the friends of a specific |
7
|
|
|
* user. `/users/1/friends` is a possible endpoint for that. In every method you first need to check if the user with the |
8
|
|
|
* id 1 is available in the system. |
9
|
|
|
* |
10
|
|
|
* The friends controller can extend the nested resource rest controller and is now able to handle request in an easier |
11
|
|
|
* way. |
12
|
|
|
* |
13
|
|
|
* @author Christian Blank <[email protected]> |
14
|
|
|
*/ |
15
|
|
|
abstract class NestedResourceRestController extends BaseRestController { |
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var string the error message if no id was provided for the request |
18
|
|
|
*/ |
19
|
|
|
protected static $no_id_message = "No id provided."; |
20
|
|
|
/** |
21
|
|
|
* @var int the error code for a not provided id |
22
|
|
|
*/ |
23
|
|
|
protected static $no_id_error = 404; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Get called by the action handler of BaseRestController. Tries to fetch the root resource. |
27
|
|
|
* |
28
|
|
|
* @param SS_HTTPRequest $request a http request |
29
|
|
|
* @param string $action the name of the action (eg. post, put, get, delete) |
30
|
|
|
* @return array the result of the action call |
31
|
|
|
* @throws RestSystemException |
32
|
|
|
* @throws RestUserException |
33
|
|
|
*/ |
34
|
|
|
public final function beforeCallActionHandler(SS_HTTPRequest $request, $action) { |
|
|
|
|
35
|
|
|
$id = $request->param(Config::inst()->get('NestedResourceRestController', 'root_resource_id_field')); |
36
|
|
|
if(!$id) { |
37
|
|
|
throw new RestUserException(static::$no_id_message, static::$no_id_message); |
38
|
|
|
} |
39
|
|
|
$resource = $this->getRootResource($id); |
40
|
|
|
if(!$resource) { |
41
|
|
|
SS_Log::log("NoResourceError was not handled inside the controller", SS_Log::WARN); |
42
|
|
|
throw new RestSystemException("NoResourceError was not handled inside the controller", 501); |
43
|
|
|
} |
44
|
|
|
// call the action and inject the root resource |
45
|
|
|
return $this->$action($request, $resource); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* |
50
|
|
|
* The result of this method will be injected in all method calls in the controller. |
51
|
|
|
* |
52
|
|
|
* @param string $id the `ID` param in the request |
53
|
|
|
* @return mixed |
54
|
|
|
*/ |
55
|
|
|
protected abstract function getRootResource($id); |
|
|
|
|
56
|
|
|
|
57
|
|
|
} |
58
|
|
|
|
You can fix this by adding a namespace to your class:
When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.