Zend_Auth_Adapter with multiple identity columns (username and email)

I’ve just started working with the Zend Framework and I must say it’s awesome. So powerful and so many helpers in place to make things easy to do. I’ve just been working with an authentication adapter. I wanted my users to be able to login using either their username or email address and a password. Zend_Auth_Adapter_DbTable does a brilliant job of using one field (email or username) but does not allow you to use both.

To do this I’ve written an auth adapter which has allowed me to use both. It’s a very simple class that adds an additional where clause option with the additional field. See below for the code…

 

class ZendExt_Auth_Adapter_MultiColumnDbTable 
              extends Zend_Auth_Adapter_DbTable
{
  protected $_alternativeIdentityColumn = null;
 
  protected function _authenticateCreateSelect()
  {
    $select = parent::_authenticateCreateSelect();
 
    if(isset($this->_alternativeIdentityColumn))
    {
      $select->orWhere($this->_zendDb->quoteIdentifier(
                      $this->_alternativeIdentityColumn, true) . ' = ?', 
                      $this->_identity);
    }
 
    return $select;
  }
 
  public function setAlternativeIdentityColumn($alternativeIdentityColumn)
  {
    $this->_alternativeIdentityColumn = $alternativeIdentityColumn;
    return $this;
  }
}

Pretty simple really. The important line is the “orWhere” bit which adds the additional column you want to use.
To use it you just have to do the following…

$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new ZendExt_Auth_Adapter_MultiColumnDbTable($dbAdapter);
$authAdapter->setTableName('user_user')
  ->setIdentityColumn('username')
  ->setAlternativeIdentityColumn('email')
  ->setCredentialColumn('password')
  ->setCredentialTreatment('MD5(?)');

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">