在zend框架2中的模型中获取数据库适配器

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

<?php
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,
        'users',
        'username',
        'password'
        );

        $authAdapter
        ->setTableName('users')
        ->setIdentityColumn('username')
        ->setCredentialColumn('password');


        $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?

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(
         PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
     ),
 ),
 'service_manager' => array(
     'factories' => array(
         'Zend\Db\Adapter\Adapter'
                 => '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.

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.