There are two provided ways to use Zend_Auth adapters:
indirectly, through
Zend_Auth::authenticate()directly, through the adapter's
authenticate()method
The following example illustrates how to use a Zend_Auth adapter
indirectly, through the use of the Zend_Auth class:
<?php
// Get a reference to the singleton instance of Zend_Auth
$auth = Zend_Auth::getInstance();
// Set up the authentication adapter
$authAdapter = new MyAuthAdapter($username, $password);
// Attempt authentication, saving the result
$result = $auth->authenticate($authAdapter);
if (!$result->isValid()) {
// Authentication failed; print the reasons why
foreach ($result->getMessages() as $message) {
echo "$message\n";
}
} else {
// Authentication succeeded; the identity ($username) is stored
// in the session
// $result->getIdentity() === $auth->getIdentity()
// $result->getIdentity() === $username
}
Once authentication has been attempted in a request, as in the above example, it is a simple matter to check whether a successfully authenticated identity exists:
<?php
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
// Identity exists; get it
$identity = $auth->getIdentity();
}
To remove an identity from persistent storage, simply use the
clearIdentity() method. This typically would be used for
implementing an application "logout" operation:
<?php
Zend_Auth::getInstance()->clearIdentity();
When the automatic use of persistent storage is inappropriate for a particular use
case, a developer may simply bypass the use of the Zend_Auth
class, using an adapter class directly. Direct use of an adapter class involves
configuring and preparing an adapter object and then calling its
authenticate() method. Adapter-specific details are discussed
in the documentation for each adapter. The following example directly utilizes
MyAuthAdapter:
<?php
// Set up the authentication adapter
$authAdapter = new MyAuthAdapter($username, $password);
// Attempt authentication, saving the result
$result = $authAdapter->authenticate();
if (!$result->isValid()) {
// Authentication failed; print the reasons why
foreach ($result->getMessages() as $message) {
echo "$message\n";
}
} else {
// Authentication succeeded
// $result->getIdentity() === $username
}




