Foreword
Zend Framework is excellent; this series of posts entitled ‘Zend Framework Pitfalls’ won’t try and dispute that. There are, however, one or two problems and poorly implemented components that can cause problems. Before using any library component it is important to be aware of any drawbacks and issues. It is then possible to make an objective decision before investing your time, and you can avoid banging your head against the desk understanding a known bug or problem that isn’t well documented.
Component
Priority
Minor (definition)
Problem
Zend_Auth is implemented as a singleton. This singleton references a single instance of Zend_Auth_Storage_Interface, used to persist an identity. This makes management of two or more authentication systems (e.g. frontend and admin) difficult. You must manually set the storage each time you want to query a different identity.
Solution 1 – Don’t use multiple authentication systems
In most simple web applications, you can use a single user database (table) to store both common users and administrators, and expose administrator privileges as appropriate via Zend_Acl or similar.
Solution 2 – Toggle storage
Zend_Auth has a method for changing storage, setStorage. Calling this method every time before retrieving the identity object is viable, but you have to remember to do so every time or you could read the wrong storage. This can be wrapped up for practicality:
class My_Auth extends Zend_Auth { public static function getInstance($storageNamespace = 'Zend_Auth'){ // set namespace $this->setStorage(new Zend_Auth_Storage_Session($storageNamespace)); return parent::getInstance(); } }
Remember to use this getInstance method every time you need to access your auth (and namespace) rather than storing a reference to the Zend_Auth instance.
Solution 3 – Your own implementation of Zend_Auth
Zend_Auth doesn’t actually do much heavy lifting. You could write something that can take advantage of the other Zend_Auth_* components, without implementing the singleton pattern. This is suggested in the reference manual.
Summary
It is unlikely that Zend_Auth will be re-architected for the 2.0 release of Zend Framework, the earliest opportunity for a break in backwards compatibility. Whether the singleton pattern is appropriate is debatable and a strongly advantageous alternative solution would be necessary to justify any changes.
As always, your comments and solution suggestions are welcomed.