Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Request;
- require_once('Track.php');
- abstract class Request {
- protected $class = null;
- protected $response = null;
- //
- protected function __construct($data) {
- $this->class = $data['class'];
- }
- public function getResponse() {
- if($this->response === null)
- $this->process();
- return $this->response;
- }
- protected abstract function process();
- //
- public function log($f = 'foo') {
- $s = print_r($this, true);
- //file_put_contents($f, $s);
- echo "<pre>$s</pre>";
- }
- //
- public static function parse($data) {
- switch($data['type']) {
- case 'get':
- return new Get($data);
- case 'update':
- return new Update($data);
- case 'add':
- return new Add($data);
- case 'delete':
- return new Delete($data);
- default:
- throw new Exception('Unknown/Unsupported request type: '.$data['type']);
- }
- }
- }
- //
- class Get extends Request {
- protected $constraint = null;
- //
- public function __construct($data) {
- parent::__construct($data);
- $this->constraint = $data['constraint'];
- }
- //
- protected function process() {
- $this->response = \DataCore::jsonRequest($this->class, $this->constraint);
- return $this;
- }
- }
- //
- class Update extends Request {
- protected $json = null;
- //
- public function __construct($data) {
- parent::__construct($data);
- $this->json = $data['data'];
- }
- protected function process() {
- $data = json_decode($this->json);
- $target = new $this->class($data->id);
- $target->update($data);
- $this->response = 'Update applied';
- return $this;
- }
- }
- //
- class Add extends Request {
- protected $json = null;
- protected $obj = null;
- //
- public function __construct($data) {
- parent::__construct($data);
- $this->json = $data['data'];
- }
- protected function process() {
- $class = $this->class;
- try {
- $this->obj = $class::addJSON($this->json);
- $this->response = json_encode($this->obj);
- }
- catch(\PDOException $e) {
- $this->response = json_encode([
- 'success' => false,
- 'error' => [
- 'code' => $e->errorInfo[0],
- 'message' => $e->errorInfo[2],
- ],
- ]);
- }
- return $this;
- }
- }
- //
- class Delete extends Request {
- //
- protected $id = null;
- //
- public function __construct($data) {
- parent::__construct($data);
- $this->id = $data['id'];
- }
- //
- protected function process() {
- $class = $this->class;
- $class::remove($this->id);
- $this->response = 'Record removed from DB';
- return $this;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement