You are free to browse all of the content on this site, however if you want to post comments or replies you will need to register for a free account. Becoming a registered member also disables some of the more annoying ads whilst you are logged in.

Authentication with Zend framework 2 and Doctrine 2

My latest development project (Fall of empires: Intergalatic) is being built using the brand new Zend framework 2 and Doctorine ORM due to the youth of the former I was unable to find any documentation on how to setup authentication in zend framework 2 using the doctrine 2 authenication adapter, so to save others on scouring the code for clues on how to do it here it is.

Step 1
You will need to define your user entity. The relevant part of my entity is as follows:

This user model (named player in my system) defines a username property (the players IDENTITY) and a password property (the players CREDENTIAL) i've also shown the setter and getter for password and a static function hashPassword. This method is used by doctrine to compare the supplied password to the users password and should return either a boolean or the hash of $password. In my code, we use the crypt function to hash the password and compare it against the users password ourselves, returning a boolean.

Step 2
We need to setup the dependancy manager inside zend to give us back a properly configured Authenication service in our controller. (This is the bit I couldn't find any documentation on) A quick read through the code in the doctrine ORM module and a bit of experimentation suggested that the structure of the config should be as follows:

The config block should be placed inside your module.config file. You have probably already setup the driver section, it is the authentication section that is important. I have commented each property with a brief description. It's important to note that the credential property must either be public, accessable via a magic __get method or have a get<Name> method defined in your class.

Step 3
Once that is all setup, you are ready to authenticate your user in your controller. For berevity I have not included any of the form setup or handling.