dqq3623 2014-02-17 13:15
浏览 52
已采纳

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

  • 写回答

2条回答 默认 最新

  • 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(
             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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?