<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
jeffersonsimaogoncalves / cakephp-rest-api example snippets
Plugin::load('RestApi', ['bootstrap' => true]);
namespace App\Controller;
use RestApi\Controller\ApiController;
/**
* Foo Controller
*/
class FooController extends ApiController
{
/**
* bar method
*
*/
public function bar()
{
// your action logic
// Set the HTTP status code. By default, it is set to 200
$this->httpStatusCode = 200;
// Set the response
$this->apiResponse['you_response'] = 'your response data';
}
}
namespace App\Controller;
use RestApi\Controller\ApiController;
use RestApi\Utility\JwtToken;
/**
* Account Controller
*
*/
class AccountController extends ApiController
{
/**
* Login method
*
* Returns a token on successful authentication
*
* @return void|\Cake\Network\Response
*/
public function login()
{
$this->request->allowMethod('post');
/**
* process your data and validate it against database table
*/
// generate token if valid user
$payload = ['email' => $user->email, 'name' => $user->name];
$this->apiResponse['token'] = JwtToken::generateToken($payload);
$this->apiResponse['message'] = 'Logged in successfully.';
}
}
namespace App\Controller;
use RestApi\Controller\ApiController;
/**
* Articles Controller
*
* @property \App\Model\Table\ArticlesTable $Articles
*/
class ArticlesController extends ApiController
{
/**
* index method
*
*/
public function index()
{
$articles = $this->Articles->find('all')
->select(['id', 'title'])
->toArray();
$this->apiResponse['articles'] = $articles;
}
}
namespace App\Controller;
use RestApi\Controller\ApiController;
/**
* Foo Controller
*
*/
class FooController extends ApiController
{
/**
* bar method
*
*/
public function restricted()
{
$this->request->allowMethod('post');
// your other logic will be here
// and finally set your response
// $this->apiResponse['you_response'] = 'your response data';
}
}
namespace App\Controller;
use Cake\Network\Exception\NotFoundException;
use RestApi\Controller\ApiController;
/**
* Foo Controller
*
*/
class FooController extends ApiController
{
/**
* error method
*
*/
public function error()
{
$throwException = true;
if ($throwException) {
throw new NotFoundException();
}
// your other logic will be here
// and finally set your response
// $this->apiResponse['you_response'] = 'your response data';
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.