4 * A simple application controller extension
6 class Users extends ApplicationController {
9 * Retrieves rows from database.
11 public function view() {
12 $res = new Response();
14 $res->message = "Loaded data";
15 $res->data = User::all();
16 return $res->to_json();
21 public function create() {
22 $res = new Response();
24 // Ugh, php...check if !hash
25 if (is_array($this->params) && !empty($this->params) && preg_match('/^\d+$/', implode('', array_keys($this->params)))) {
26 foreach ($this->params as $data) {
27 array_push($res->data, User::create($data)->to_hash());
30 $res->message = "Created " . count($res->data) . ' records';
32 if ($rec = User::create($this->params)) {
34 $res->data = $rec->to_hash();
35 $res->message = "Created record";
37 $res->success = false;
38 $res->message = "Failed to create record";
41 return $res->to_json();
47 public function update() {
48 $res = new Response();
50 if (is_array($this->params)) {
52 foreach ($this->params as $data) {
53 if ($rec = User::update($data->id, $data)) {
54 array_push($res->data, $rec->to_hash());
58 $res->message = "Updated " . count($res->data) . " records";
60 if ($rec = User::update($this->params->id, $this->params)) {
61 $res->data = $rec->to_hash();
63 // SIMULATE ERROR: All records having odd-numbered ID have error.
65 $res->success = false;
66 $res->message = "SIMULATED ERROR: Lorem ipsum dolor sit amet, placerat consectetuer, nec lacus imperdiet velit dui interdum vestibulum, sagittis lectus morbi, urna aliquet minus natoque commodo egestas non, libero libero arcu sed sed.";
69 $res->message = "Updated record";
72 $res->message = "Failed to updated record " . $this->params->id;
73 $res->success = false;
77 return $res->to_json();
83 public function destroy() {
84 $res = new Response();
85 if (is_array($this->params)) {
87 foreach ($this->params as $rec) {
88 if ($rec = User::destroy($rec->id)) {
89 array_push($destroyed, $rec);
93 $res->message = 'Destroyed ' . count($destroyed) . ' records';
95 if ($rec = User::destroy($this->params->id)) {
96 $res->message = "Destroyed User";
99 $res->message = "Failed to Destroy user";
102 return $res->to_json();