CakePHP mapping HTTP request to the correct action

2019-09-14 21:56发布

问题:

I have been trying to set up RESTful functionality in my app and I face a problem of whatever action I call it is router to that particular controllers index action. I have been trying to call add and view actions, but they are just not being routed properly. Here is the resposne I get when trying to call the view action:

{"code":404,"url":"\/application\/rest_customers\/54.json","name":"Action RestCustomersController::54() could not be found."}

And here is the way it is all set up in. RestCustomersController:

class RestCustomersController extends AppController {

    public $uses = array('Customer');
    public $helpers = array('Html', 'Form');
    public $components = array('RequestHandler');

    public function index() {
    }

    public function view($id=null){

    $customer = $this->Customer->find('first', array(
          'conditions'=>array('Customer.id'=> $id)));

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

Here are the routes:

Router::mapResources('customers');
Router::parseExtensions('json', 'xml', 'csv', 'pdf');

And here os the AppControllers beforeFitler function:

if(in_array($this->params['controller'], array('rest_customers'))){
    $this->Auth->allow();
    $this->Security->unlockedActions = array('add','index', 'view');
}else{
    $this->Security->unlockedActions = array('add', 'edit');
    $this->Auth->allow('index', 'view');
    $this->set('logged_in', $this->Auth->loggedIn());
    $this->set('current_user', $this->Auth->user());
}}

Any help is very much appreciated.

回答1:

You are creating REST routes for a controller named Customers, but you are actually accessing a controller named RestCustomers, so what you are experiencing is the expected behavior as there simply are no REST routes connected for the RestCustomers controller.

You should either rename your controller to CustomersController, or change your mapping to use the correct name so that it will connect the routes to RestCustomersController

Router::mapResources('rest_customers');