0
votes

I'm trying to set up a routing definition in my project which will allow users to have profiles accessible by simply using their username as the only parameter in the url, like www.example.com/username as opposed to www.example.com/user/view/username

I've set up a catch all route to go to an action which checks if the user exists, as the last route in the config file, and it works, but it over rides all of the basic routing that cake does. Meaning that I would have to define a route for every controller I want to provide access to just to make sure I never make it to the catchall. My routes:

Router::connect('/events/edit/*', array('controller' => 'events', 'action' => 'edit'));
Router::connect('/events/view/*', array('controller' => 'events', 'action' => 'view'));
Router::connect('/events/add', array('controller' => 'events', 'action' => 'add'));
Router::connect('/events/*', array('controller' => 'events', 'action' => 'index'));
Router::connect('/*', array('controller' => 'users', 'action' => 'view'));

So, this will allow me to access my events page, but any other pages get sent to the second router, expectedly.

What I'd like is to have is a route that does the basic cake function of /controller/action/param if the controller exists, but have it fall through to the last route which goes to the user/view page otherwise.

My question is, for what I'm trying to accomplish, am I doing this the right way? If I need to define a route for every controller I want access to, I will, but I have to think there's a better way to accomplish this.

Thanks

1

1 Answers

1
votes

According to the my understanding of your question, I think You can proceed like this.

App::uses('UserRoute','Lib');
Router::connect('/:user_name', array('controller' => 'users', 'action' => 'view'),
array('routeClass'=>'UserRoute', 'pass' => array('user_name')));

and in your app/lib create a file UserRoute.php like this

<?php

App::uses('Lib', 'CakeRoute');

class UserRoute extends CakeRoute {

    function parse($url) {

        $params = parent::parse($url);

        if (empty($params)) {
            return false;
        }

        App::import('Model', 'User');
        $User = new User();
        $user_count = $User->find('count',array(
            'conditions' => array('User.username' => $params['user_name']),
            'recursive' => -1 
        ));

        if ($user_count) {
            return $params;
        }

        return false;
    }

}

Hope this will help you..