2014-02-17 13:15 阅读 47


I am a zf1 developer. I started zf2. I am creating a Authentication module. I created a Auth class as mentioned in the doc

namespace Application\Model;
use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;

class Myauth implements AdapterInterface {

     * Sets username and password for authentication
     * @return void
    public function __construct($username, $password) {

        // Configure the instance with constructor parameters...
        $authAdapter = new AuthAdapter($dbAdapter,


        $result = $authAdapter->authenticate();

        if (!$result->isValid()) {
            // Authentication failed; print the reasons why
            foreach ($result->getMessages() as $message) {
                echo "$message
        } else {
            // Authentication succeeded
            // $result->getIdentity() === $username


Issue1 : How to get $dbAdapter here? Issue2 : Is this correct way to create auth module?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    douyi4544 douyi4544 2014-02-17 14:23

    I have a couple things to say:

    1. About Database Adapter

    This link shows you how to configure database adapter.

    In config/autoload/global.php:

     return array(
     'db' => array(
         'driver'         => 'Pdo',
         'dsn'            => 'mysql:dbname=zf2tutorial;host=localhost',
         'driver_options' => array(
     'service_manager' => array(
         'factories' => array(
                     => 'Zend\Db\Adapter\AdapterServiceFactory',

    In config/autoload/local.php:

     return array(
         'db' => array(
             'username' => 'YOUR USERNAME HERE',
             'password' => 'YOUR PASSWORD HERE',

    Now, from ServiceLocatorAware classes, you can get Database Adapter as

    $dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');

    2. About Creating Authentication

    Dude, why reinvent the square wheel? As mentioned here, ZfcUser is built to be a foundation for a very large percentage for Zend Framework 2 applications.

    Nearly anything is customizable as mentioned here. A lot of modules are available such as ScnSocialAuth which have dependancy on ZfcUser and are really awesome.

    点赞 10 评论 复制链接分享
  • dowy77780 dowy77780 2015-07-26 18:37

    As in ZF 2, Models are not ServiceLocatorAware classes, so you cannot use the solution in Ojjwal Ojha's answer.

    You can: 1. Get dbAdapter in your Controller by calling:

    $dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');

    1. Pass dbAdapter to your Model when you create it:

      $model = new Model($dbAdapter);

    2. Write an init function in your Model.

    点赞 2 评论 复制链接分享