Recently, I wrote a simple web application. I currently have.
For each object I need to manipulate, the server provides a php script at /app/object.php
which accepts POST data and return JSON results.
Eg (not actual responses):
POST /app/comments.php?a=add&page_id=43&author=A&text=Some%20Text
{"s":"OK"}
POST /app/comments.php?a=list&page_id=43
[{ "author": 'A', "text": "Some text"}, { "author": "B", "text": "Other text"}]
POST /app/users.php?a=list
["A", "B", "C"]
Under the hood the JSON api is implemented like that:
//comments.php
require('init.php');
// start sessions, open database connections with data in config.php
switch(POST('a')){
case "list":
//.... retrieving data
echo json_encode($data)
break;
case "add":
//.... inserting data
echo '{"s":"OK"}';
break;
}
The largest object has 7 methods and 200 (well-indented, not compressed) LOC, while the average is roughly 3 methods per object.
A developer friend of mine is suggesting to replace the switch with objects, to make it "simpler", "more extensible" and "more maintainable".
I frankly don't see how a system like that could get any simpler (especially by using objects) but I'd love to know other developers' opinions.
Ignoring the performance hit of using objects in PHP, should I use a class-based approach?
If yes, how can I structure my JSON API in order to use objects, without adding too much code (and thus decreasing the maintainability of the project)?
<?php
class Controller {
protected $post;
public function __construct() {
$this->post = $post;
}
public function __call($name, $arguments) {
if(!method_exists($this, $name)) {
die("Unknown action!");
}
}
public function whatever() {
echo json_encode($this->post['page_id']);
}
public function data() {
echo '{"s":"OK"}';
}
// new action? just add another method
}
$controller = new Controller();
$controller->{$_POST('a')}(); // example 1
$controller->data(); // you can't do it using switch