I’ve recently read this article about entity based routing in CakePHP 3 and thought that this, somehow, could be done for CakePHP 2.0 as well. So I wrote the LinkHelper for CakePHP 2.0 which is now part of my BzUtils plugin.

The biggest difference here is that CakePHP 2 doesn’t use entity objects, instead we have to deal with an array. The downside of the solution for CakePHP 2 is, that it doesn’t work fully automated but you’ll have to write a config for each kind of URL but this gives you as well more control over the URL but still decreases the amount of code you have to write for all your links on your page. You won’t have to do more than just passing the array data to a helper method and provide and identifier. An advantage of my solution is that it can deal with associated data as well. This could be added to the entity route class for 3.0 as well.

So the ideal case would be just something like this:

The result of that call will be:

If you only want to generate the URL, you can do this as well:

How does that work?

First you’ll need your route, as usual:

Now the link building magic: You’ll have to provide a config for each data structure you want to turn into a link. You can put this into bootstrap.php or put it in a separate config file and load it in bootstrap.php. A full featured example might look this:

The title and alias are optional. But you’ll require the title if you want to use that feature and you’ll have to use the alias if your primary models name in the array structure changes for whatever reason. The preset is the URL you want to use, the fieldMap is a mapping of URL params to the array data you pass to the helper that will be turned into the link.

Wherever you now need that link you can simply use the LinkHelper to generate that link. When you need to change the URL some day you’ll just have to change a single place – the config for the URL. This might not sound that great if you have a small application but if you have a large site with many places using the same links this is something really nice to have.