Search code examples
phpregexroutescakephpfriendly-url

CakePHP Username URL using Regex?


I found a comment here: http://bakery.cakephp.org/articles/PHPdiddy/2006/10/06/custom-urls-from-the-site-root

That said:

Just change last line.
Router::connect('/', array('controller' => 'members', 'action' => 'show'));
to
Router::connect('(?!admin|items|images)(.
*)', array('controller' => 'members', 'action' => 'show'));

Some people were able to get that to work... It didn't look quite right to me though so I tried the following, but still had no luck:

Router::connect('(?!/admin|/items|/images)(/.*)',
array('controller' => 'members','action' => 'show'));

In any case, the goal is to have a url like http://domainname/username , map to a users unique id. It works with /*, but I rather not use that method. Ideas?

Update to solution: I used the selected answer below and added the following. It may be helpful to someone else.

$misc = array(*your misc webroot, admin route items here...*);
$notList = array_merge(Configure::listObjects('plugin'),Configure::listObjects('controller'));
$notListLowerCase = array();
foreach ($notList as $key=>$item):
    $notListLowerCase[] = strtolower(preg_replace("/(.)([A-Z])/","\\1_\\2",$item));
endforeach;
$notList = array_merge($notList,$misc,$notListLowerCase);
$notList = implode('|', $notList);

Router::connect('/:username', 
        array(
            'controller'=>'users', 
            'action'=>'view'
        ),   
        array(
            'username' => '\b(?:(?!'.$notList.')\w)+\b'
        )
    );

Solution

  • Here ya go. You need to capture it as a param and then reference it in the regex. The username will be available in $this->params['username'] in the controller action.

    Router::connect('/:username', 
        array(
            'controller'=>'members', 
            'action'=>'show'
        ),   
        array(
            'username' => '\b(?:(?!admin|items|images)\w)+\b'
        )
    );