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



我是 zf1 开发人员。我开始了 zf2。我正在创建一个身份验证模块。我创建了一个文档中提到的身份验证类

<?php
namespace ApplicationModel;
use ZendAuthenticationAdapterAdapterInterface;
use ZendAuthenticationAdapterDbTable 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 "$messagen";
            }
        } else {
            // Authentication succeeded
            // $result->getIdentity() === $username
        }
    }
}

问题1:如何在这里获得$dbAdapter?问题 2:这是创建身份验证模块的正确方法吗?

我有几件事要说:

1. 关于数据库适配器

此链接说明如何配置数据库适配器。

在配置/自动加载/全局.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(
         'ZendDbAdapterAdapter'
                 => 'ZendDbAdapterAdapterServiceFactory',
     ),
 ),
);

在配置/自动加载/本地.php中:

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

现在,从ServiceLocatorAware类中,您可以获得数据库适配器作为

$dbAdapter = $this->getServiceLocator()->get('ZendDbAdapterAdapter');

2. 关于创建身份验证

伙计,为什么要重新发明方形轮子?正如这里提到的,ZfcUser 是为 Zend Framework 2 应用程序提供很大比例的基础。

几乎任何东西都是可定制的,如此处所述。有很多模块可用,例如ScnSocialAuth,它们依赖于ZfcUser并且非常棒。

与 ZF 2 一样,模型不是 ServiceLocatorAware 类,因此您不能在 Ojjwal Ojha 的答案中使用解决方案。

您可以:1. 通过调用以下命令在控制器中获取 dbAdapter:

$dbAdapter = $this->getServiceLocator()->get('ZendDbAdapterAdapter');

  1. 在创建模型时将 dbAdapter 传递给它:

    $model = new Model($dbAdapter) ;

  2. 在模型中编写一个 init 函数。

最新更新