megous / ajax-todo-list

Simple "host it yourself" todo list. An example of simple Prototype JS based client side MVC design.

This URL has Read+Write access

ajax-todo-list / rpc-lib.php
100644 82 lines (65 sloc) 1.64 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
 
require_once 'JSON.php';
 
if (!function_exists('json_decode'))
{
  function json_decode($content, $assoc=false)
  {
    if ($assoc)
      $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
    else
      $json = new Services_JSON;
 
    return $json->decode($content);
  }
}
 
if (!function_exists('json_encode'))
{
  function json_encode($content)
  {
    $json = new Services_JSON;
 
    return $json->encode($content);
  }
}
 
abstract class rpc_server
{
  protected function _exec($method, $params)
  {
    if (!method_exists($this, $method))
      throw new Exception("Unknown method {$method}!");
 
    if (($retval = $this->_pre_call($method, $params)) !== null)
      return $retval;
 
    $retval = call_user_func_array(array($this, $method), $params);
 
    return $this->_post_call($method, $params, $retval);
  }
 
  protected function _pre_call($method, $params)
  {
    return null;
  }
 
  protected function _post_call($method, $params, $retval)
  {
    return $retval;
  }
 
  abstract public function run();
}
 
class json_rpc_server extends rpc_server
{
  public function run()
  {
    $return = new stdClass;
    $return->version = "1.1";
 
    try
    {
      $request = json_decode(file_get_contents('php://input'));
      if (!$request)
        throw new Exception("Invalid RPC call.");
      $return->result = $this->_exec($request->method, $request->params);
    }
    catch (Exception $ex)
    {
      $return->error = array('name' => 'JSONRPCError', 'code' => $ex->getCode(), 'message' => $ex->getMessage());
    }
 
    header('Content-Type: application/json');
    echo json_encode($return);
    exit(0);
  }
}
 
?>