Tag: cakephp router

Dealing with static pages v2 (or… 3?)

Over the years of cake development we’ve seen a number of ways to get rid of the the /pages/ path in the URL for static pages.

By default if you create an “about us” page, such as in app/views/pages/about.ctp, the resulting URL would be:
www.example.com/pages/about

I’m sure you’ve seen a ton of complaints and solutions about how to get rid of this seemingly “annoying” /pages/
To keep the URL’s clean, most people would obviously prefer to have www.example.com/about instead. (No /pages/ in sight).

Recently, my favorite solution has become the following setting in the routes.php:

$staticPages = array(
    'about',
    'legal',
    'policy',
    'something'
);

$staticList = implode('|', $staticPages);

Router::connect('/:static', array(
    'plugin' => false,
    'controller' => 'pages',
    'action' => 'display'), array(
        'static' => $staticList,
        'pass' => array('static')
        )
    );

Go ahead, create your about.ctp and then attempt to access it by going to www.yoursite.com/about

The Router will nicely remove the /pages/ from the URL.

Q.
Why keep the pages in the array() and then use implode()? Couldn’t I just have the following?

$staticList = 'about|legal|policy|something';

A.
You sure could, but array structure allows to keep things organized neater and if you have a large amount of pages it’s easier to scan visually to insert/remove pages as necessary. Either way, you have both options to work with.

Overriding default URL's (aka persistent routes)

CakePHP’s routes allow for an easy way to serve content by using URL aliases.

Let’s take an example from the manual:

Router::connect(
    '/cooks/:action/*', array('controller' => 'users', 'action' => 'index')
);

By having the user access the URL such as example.com/cooks/index simply shows the default view for example.com/users/index (as was our intention).

However, if you have a bunch of links on that page, which point to other actions in the Users controller, the URL’s will remain as example.com/users/some_other_action. In some cases it may not be desired, i.e. if a visitor entered the section of your site by using the “cooks” URL, you don’t want to suddenly confuse them by presenting a completely different link to other actions. Otherwise, you may simply wish to be consistent (or sneaky).

A simple override of the Helper::url() method allows us to solve this problem.
(Place the following in your app_helper.php)

public function url($url = NULL, $full = FALSE) {
  if(strstr($this->params['url']['url'], 'cooks') && $url['controller'] == 'users') {
    $url['controller'] = 'cooks';
  }

  return parent::url($url, $full);
}

That’s it, now any link that would otherwise point to example.com/users/some_other_action will now point to example.com/cooks/some_other_action.

p.s. You might want to add an additional check: isset($url['controller'])