CakePHP:Esempio di Controller che risponde ad una richiesta REST tramite protocollo JSON
CakePHP REST: https://book.cakephp.org/3/en/development/routing.html#resource-routes
E' possibile testare chiamata e risposta tramite il componente aggiuntivo di Firefox RESTClient
Traduzione automatica per le chiamare JSON
HTTP format URL.format Controller action invoked --------------------------------------------------------------------- GET /tests.json TestsController::index() GET /tests/123.json TestsController::view(123) POST /tests.json TestsController::add() PUT /tests/123.json TestsController::edit(123) PATCH /tests/123.json TestsController::edit(123) DELETE /tests/123.json TestsController::delete(123)
Esempio
File del plugin "Sync"
File config/routes.php
<?php
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\Router;
Router::scope( '/sync', ['plugin' => 'Sync'],
function ( Cake\Routing\RouteBuilder $routes) {
$routes->extensions(['json']);
$routes->resources('Tests');
}
);
Controller di test
File src/Controller/TestsContoller.php
<?php
namespace Sync\Controller;
use Sync\Controller\AppController;
/**
* Foo Controller
*
*/
class TestsController extends AppController {
public function index() {
$result = [
[ 'id' => 1, 'description' => 'desc 1' ],
[ 'id' => 2, 'description' => 'desc 2' ],
];
$this->set([
'result' => $result,
'_serialize' => ['result']
]);
}
public function view( $id = null ) {
$result = [
'id' => $id,
'description' => 'description '.$id
];
$this->set([
'result' => $result,
'_serialize' => ['result']
]);
}
public function add( ) {
$this->request->allowMethod(['post']);
$result = [
'data' => $this->request->data
];
$this->set([
'result' => $result,
'_serialize' => ['result']
]);
}
public function edit( ) {
$this->request->allowMethod(['put']);
$result = [
'data' => $this->request->data
];
$this->set([
'result' => $result,
'_serialize' => ['result']
]);
}
public function delete( ) {
$this->request->allowMethod(['delete']);
$result = [
'data' => $this->request->data
];
$this->set([
'result' => $result,
'_serialize' => ['result']
]);
}
}