phpcakephpcakephp-routing

Cakephp routing controller alias


I'm trying to do the same as this site, stackoverflow, do with their URLs.

CakePHP works like this: website/controller/action/

I want to config routing to achieve this:

myWebSite.com/questions/(question_id)/(question)/

eg: myWebSite.com/questions/12874722/cakephp-routing-controller-alias /

I didnt figured it out how to do this bold part of URL.


Solution

  • In your Config/routes.php

    Router::connect('/questions/*', array('controller' => 'questions', 'action' => 'view'));
    

    In Controller/QuestionsController.php

    view action get question id as

    public function view() {
        $question_id = isset($this->request->params['pass'][0]) ? $this->request->params['pass'][0] : "";
        $question = isset($this->request->params['pass'][1]) ? $this->request->params['pass'][1] : "";
    
        if( empty($question_id) ) {
            throw new NotFoundException('Could not find that question');
        }
    
        // if $question is empty then get slug from database and redirect to /question_id/question
    
    
        // Get question details and set
    }