The CakePHP framework API is a treasure trove of often undiscovered methods and functionality. Recently I came across the Inflector Class methods and noticed the “slug” method close to the bottom of the documentation, which is documented thus:
Returns a string with all spaces converted to underscores (by default), accented characters converted to non-accented characters, and non word characters removed.
Slug is the perfect method for generating a search engine friendly URL from any string. For instance in an application I am currently developing there is a categories model with a field called title. This makes a great field to automagically convert to a url part for SEO purposes. Now instead of a URL like /category/browse/1 ; I can have something like /category/browse/1/restauraunts-cafes-and-bars.
For my taste of URL structure slug doesn’t work perfectly out of the box: it uses underscores to seperate words, rather than hypens; and it doesn’t convert all characters to lower-case. Having said that, a workable solutions is never far away in CakePHP.
The easiest solution for me is to build a reusable method in my /app/controllers/app_controller.php that I can access from any other controller or view. This way I can create a slug on the fly in my view or commit them to my database on create or update. So, let me introduce my hyper-simple private method, toSlug() :
function _toSlug($string) {
return low(Inflector::slug($string, '-''));
}
Call this method like this:
$this->_toSlug("Any String or Data You like")
Which returns any-string-or-data-you-like
Hi Tim, I’ve also written something similar at
http://www.davidtan.org/seo-building-pretty-url-slugs-with-cakephp/
with something extra about taking care of utf8 text, hope someone will find that useful too.