Skip to content

Instantly share code, notes, and snippets.

@sergiopvilar
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergiopvilar/10000950 to your computer and use it in GitHub Desktop.
Save sergiopvilar/10000950 to your computer and use it in GitHub Desktop.
Criando uma API REST com CakePHP
<?php echo json_encode($data); ?>
<?php
/**
* Created by PhpStorm.
* User: sergiovilar
* Date: 05/04/14
* Time: 11:44 PM
*/
class RestController extends AppController{
public function index($id = null) {
switch($this->request->method()){
case 'GET':
if(!empty($id)){
$this->view($id);
}else{
$this->listAll();
}
break;
case 'POST':
if(!empty($id)){
$this->add();
}else{
$this->update($id);
}
break;
case 'PUT':
$this->update($id);
break;
case 'DELETE':
$this->delete($id);
break;
}
}
// Métodos privados
private function renderJSON(){
$this->layout = null;
$this->set('data', array('result' => $this->out));
$this->render('/Elements/json');
}
private function returnError($error){
$this->layout = null;
$this->set('data', array('error' => $error));
$this->render('/Elements/json');
}
private function returnSuccess($msg){
$this->layout = null;
$this->set('data', array('success' => $msg));
$this->render('/Elements/json');
}
protected function listAll(){
$this->out = $this->{$this->model}->find('all');
$this->renderJSON();
}
private function view($id){
$this->out = $this->{$this->model}->findById($id);
$this->renderJSON();
}
protected function add() {
$this->{$this->model}->create();
if ($this->{$this->model}->save($this->request->data)) {
$this->returnSuccess("Registro adicionado com sucesso");
} else {
$this->returnError("Houve um problema ao adicionar o registro");
}
}
protected function update($id) {
$this->{$this->model}->id = $id;
if ($this->{$this->model}->save($this->request->data)) {
$this->returnSuccess("Registro atualizado com sucesso");
} else {
$this->returnError("Houve um problema ao atualizar o registro");
}
}
protected function delete($id) {
if ($this->{$this->model}->delete($id)) {
$this->returnSuccess("Registro excluído com sucesso");
} else {
$this->returnError("Houve um problema ao excluir o registro");
}
}
}
<?php
App::uses('AppController', 'Controller');
require_once(ROOT . DS . 'app' . DS . 'Controller' . DS . 'RestController.php');
/**
* Sample Controller
*
*/
class SampleController extends RestController {
public $model = 'Sample';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment