Creating REST API with CakePHP

2019-09-06 17:44发布

问题:

I have to create a REST API for mobile backend using CakePHP. After following the instructions here I have been able to setup the requirements for creating a REST API. The problem is that I am getting a null in my output when I use the _serialize variable. Here is my code:

class InvitationController extends AppController {

    public $components = array('RequestHandler');

    public function index() {

    }

    public function add() {

        if ($this->request->is('post')) {
            $this->loadModel('Organizer');

            $numPeople = $this->request->data['numpeople'];
            $share = $this->request->data['myshare'];
            $organizer = $this->request->data['organizer'];     
            $organizerMobile = $this->request->data['organizermobile'];
            $this->set('organizerMobile', $organizerMobile);    
            $deadline = $this->request->data['deadline'];

            $links = array();       

            date_default_timezone_set("Asia/Calcutta");
            $now = date('Y-m-d');
            $lastOrganizer = $this->Organizer->find('first', array(
                'order' => array('Organizer.id' => 'desc')
            ));

            $checkOrganizer = $this->getOrganizerDetails($lastOrganizer);

            $pass = //something;


            // save data in organizers table
            $this->organizer->create();
            $this->organizer->save(
                array(
                    'name' => $organizer,
                    'mobile' => $organizerMobile,
                    'p_id' => 1,
                    'share' => $share,
                    'deadline' => $deadline,
                    'password' => $pass,
                    'group_cardinality' => $numPeople,
                    'created_on' => $now,
                )
            );

            $message = 1;
            $this->set(array(
                'message' => $message,
                '_serialize' => array($message)
            ));
        }
    }
}   

When I make a request to POST /invitation.json I get null in the ouput with status 200. On the other hand if I simply do echo json_encode($message) in the Controller or in the View I get the correct output. I think I am doing something wrong. Please help!

回答1:

That's wrong:

 '_serialize' => array($message)

Pay attention to the manual, it shows it correctly in the provided examples.

 '_serialize' => array('message')