From 5cb40f215832e559cd7f72ba92ad00e441f38b2e Mon Sep 17 00:00:00 2001 From: Robert Sesek Date: Sat, 30 Jul 2011 17:47:14 -0400 Subject: [PATCH] Add data\Controller --- data/controller.php | 95 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 data/controller.php diff --git a/data/controller.php b/data/controller.php new file mode 100644 index 0000000..47e5990 --- /dev/null +++ b/data/controller.php @@ -0,0 +1,95 @@ +. + +namespace hoplite\data; +use \hoplite\http as http; + +require_once HOPLITE_ROOT . '/http/response_code.php'; +require_once HOPLITE_ROOT . '/http/rest_action.php'; + +/*! + A Controller is a RESTful http\Action that is used to bind a data\Model to a + web interface. Subclass this in order to perform business logic such as + validation and authentication. + + This class is semi-abstract in that it cannot be used directly. At minimum, + FilterRequest() needs to be overridden to select the Model to use. +*/ +class Controller extends http\RestAction +{ + /*! @var hoplite\data\Model The object that will be operated on. */ + protected $model = NULL; + + /*! Selects the Model object. */ + public function FilterRequest(http\Request $request, http\Response $response) + { + // Example: + // $this->model = new webapp\models\User(); + throw new ControllerException('Model not selected'); + } + + /*! Gets the data from the model. */ + protected function _DoGet(http\Request $request, http\Response $response) + { + $this->model->SetFrom($request->data); + try { + $response->data = $this->model->Fetch(); + } catch (ModelException $e) { + $response->data['message'] = $e->GetMessage(); + $response->response_code = http\ResponseCode::NOT_FOUND; + } + } + + /*! Updates an object in the store. */ + protected function _DoPost(http\Request $request, http\Response $response) + { + $this->model->SetFrom($request->data); + try { + $this->model->Update(); + $response->data = $this->model->Fetch(); + } catch (ModelException $e) { + $response->data['message'] = $e->GetMessage(); + $response->response_code = http\ResponseCode::NOT_FOUND; + } + } + + /*! Deletes the object from the store. */ + protected function _DoDelete(http\Request $request, http\Response $response) + { + $this->model->SetFrom($request->data); + try { + $this->model->Delete(); + } catch (ModelException $e) { + $response->data['message'] = $e->GetMessage(); + $response->response_code = http\ResponseCode::BAD_REQUEST; + } + } + + /*! Updates an object in the store. */ + protected function _DoPut(http\Request $request, http\Response $response) + { + $this->model->SetFrom($request->data); + try { + $this->model->Insert(); + $response->data = $this->model->Fetch(); + } catch (ModelException $e) { + $response->data['message'] = $e->GetMessage(); + $response->response_code = http\ResponseCode::BAD_REQUEST; + } + } +} + +class ControllerException extends \Exception {} -- 2.22.5