Simple links and routes with CakePHP 2.x

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.


CakePHP and token based auth (with Angular JS)

This article will show you how to set up a Json Web Token with CakePHP and Angular. This blog post is not a complete step by step tutorial but shows you the concept of the JWT Token and a high-level implementation. To follow the instructions in this article it is assumed that you know how to work with REST and JSON Views in CakePHP and Composer.

This is actually pretty easy by using php-jwt and modifying Ceerams TokenAuthenticate adapter for CakePHP. I’ve modified the nice working TokenAuthenticate adapter to work with JWT. You’ll need to add firebase/php-jwt to your composer.json or add the library otherwise to your application. You can find the JwtTokenAuthenticate for CakePHP 2.x on Github, it is part of my BzUtils plugin.

So what is the important difference between JWT and a regular Token?

The JWT token is encrypted and contains the actual user data. Usually a token is stateless and you would have to look up the user based on the token generated after login in your database. That’s what the original component did until I’ve modified it to work with JWT. The JWT token eliminates that need because it contains the actual user data, or whatever else data you want to add to it, and encrypts it. Decrypting the token every request is more efficient than querying the DB every request to lookup the user based on the token.

Pay attention to no bloating the token with unnecessary data, just store what you really need, usually the users id, username and maybe email and some authorization specific things like a role. The issue with bloating the token is that your server might not respond properly or won’t respond at all. This is because HTTP does not define any header size limit but most web servers limit the size of headers they accept. For example in Nginx it is 8KB, Apache default limit is 8KB, in IIS it’s 16K. The server will return a 413 Entity Too Large error if the headers size exceeds that limit.

To use the component add this to your AppController::beforeFilter(), you’ll still need the Form Authenticate to do the login.

Your login function has to make use of the JWT lib as well to encode the token, remember, we’re dong RESTful calls and return JSON and don’t access this via the browser directly!

This is the AngularJS component that deals with the token data. Please note that the second request right after the login is just for demonstration purpose to demonstrate that the token works by making an immediate request to a protected action.

Best practice for dealing with additional data in beforeSave()

On somebody asked how to securely set a value inside a form. Besides the obvious fact that you don’t do that if the value is not needed for some purpose in the view, one of the answers given to that question contained so much not so good code, that it inspired me to give a detailed answer as well and to write this article about it. Here is the code in question:

Short summary of what is wrong here:

  • $this->alias is not used
  • The method signature is wrong and will cause a php 5.4+ strict warning
  • Tight coupling with the Router class is introduced
  • The direct assignment of an integer value here is not good
  • The if check is not using strict === comparison

This code is introducing tight coupling with a static call and the model should not need to be aware of the Router. Also you’re missing the $options argument in the Model::beforeSave() which causes strict errors on php 5.4+ and up to date CakePHP. See this pull request for reference.

Further this couples the model code with a specific controller action and don’t even check for the controller as well. If the parameters are needed they should be passed to the model instead of accessed through a static call of the Router. In fact you can pass additional options through the second argument of the Model::save() method. The documentation doesn’t explain this very well, but if you look at the code you can pass any additional options besides the validate and callbacks options. These options are passed to the Model::beforeSave() method, which is in fact listening to the Model.beforeSave event. So in fact you could do this:

The best way to do it would be in the model because this will make sure the default group id gets always set, no matter from where the save is called and you can’t forget to pass the group id:

An alternative way is to  simply add the data in the controller method to $this->request->data but the model is the far better place because you can test the whole thing, use it in a shell and have everything in one place and the right place because all of this belongs into the model layer.