If you want to create an API, you first need to create MiddleWare , which will filter tokens, keys, etc., to make your API more secure. In addition, you should use Plugins and RESTful Routes , which will be very useful.
To create a plugin: bin/cake bake plugin Api
Create Model: bin/cake bake model Users
For example, you want to have a UserController in the Api plugin:
<?php namespace Api\Controller; use Api\Controller\AppController; use Api\Model\Table\UsersTable; class UsersController extends AppController{ public function initialize(){ parent::initialize(); $this->loadModel('Api.Users'); } public function getUser($field ='username', $username = false){ return $this->_jsonResponse( [ 'users' => $this->Users->findBy{ucfirst($field)}($username) ]; ) } public function _jsonResponse($data, $code = 200){ $this->response->type('json'); $this->response->statusCode($code); $this->response->body( json_encode((array)$data) ); return $this->response; } }
The route will be described in plugins/config/routes.php . You need to create a route map for the API in the /api path:
function (RouteBuilder $routes) { $routes->resources('Users', [ 'map' => [ 'get-user' => [ 'action' => 'getUser', 'method' => 'GET' ] ] ]); $routes->fallbacks('DashedRoute'); }
If you have frequent calls, you should use Cache , which calls and stores them for some time. For example, 10 minutes . The cache can be configured in config/app.php . You must create a separate cache prefix and use it as follows:
<?php use Cake\Cache\Cache; $data = []; Cache::write('some_key', $data, 'prefix') dump(Cache::read('some_key', 'prefix'));
These are just examples. If you have some problems - just tell me in the comments :)
Also, use migrations and seeds instead of dumping sql files
If you want to filter data from Middleware, you should have Event as an argument, which will contain the request data ( $_POST ) and request requests ( $_GET ), which you can easily handle. From the controllers, you need to use $this->request->data to get the POST data array or $this->request->query to get the GET data array.