Eric Lee Eric Lee - 8 months ago 42
PHP Question

cakephp how to send data from controller to view with json

Hi I'm trying to make an API to send data encapsulating with json.

as cakephp manual said, I added extensions in routes.php

$routes->extensions(['json]);


and I've made an index function in controller.

public function index(){
$item = $this->Items->find('all');
$this->set(['items' => $items, '_serialize' => ['items']]);
}


here are the problem.

what should i do after this to make api encapsulating with json??

Please help.

thank you

Answer

According to Cake 2.x Book (http://book.cakephp.org/2.0/en/development/rest.html)

You have to add this to your routes.php file:

Router::mapResources('items');
Router::parseExtensions();

Then, in your items controller, add the RequestHandler to your components array:

public $components = array('RequestHandler');

Then, in your items controller, add your methods, in your example:

public function index() {
    $recipes = $this->Items->find('all');
    $this->set(array(
        'items' => $items,
        '_serialize' => array('items')
    ));
}

Note: according to model names convention you should call $this->Item instead of $this->Items unless you previously defined the model name as "Item" (singular) in your item model file.

Finally, the API is done, you can access to yourprojecturl/items.json and see the json result.