php - 使用 zend 模型和 Controller 实现登录认证

标签 php extjs zend-db zend-framework2

我正在使用 Zend 2.0,我从未将 EXTJS 与 Zend 结合使用。

这是我在 view/login/index.phtml 中的 extjs 代码:

<?php $this->inlineScript()->captureStart() ?>
var LoginWindow
Ext.onReady(function() {

    LoginWindow = new Ext.create('Ext.window.Window',{
        title: 'Login',
        closable: false,
        draggable: false,
        resizable: false,
        width: 370,
        items: [
            Ext.create('Ext.form.Panel', {
                id: 'LoginForm',

                bodyPadding: 5,
                width: 350, 

                url: '/',
                layout: 'anchor',
                defaults: {
                    anchor: '100%'
                },

                // The fields
                defaultType: 'textfield',
                items: [{
                    fieldLabel: 'Username',
                    name: 'user',
                    allowBlank: false
                },{
                    fieldLabel: 'Password',
                    inputType: 'password',
                    name: 'pw',
                    allowBlank: false
                }],

                // Reset and Submit buttons
                buttons: [{
                    text: 'Reset',
                    handler: function() {
                        this.up('form').getForm().reset();
                    }
                },
                {
                    text: 'Submit',
                    formBind: true,
                    disabled: true,
                    handler: function() {
                        var form = this.up('form').getForm();

                    }
                }]
            })
        ]
    });
    Ext.getBody().mask()

    LoginWindow.show()  

});

<?php $this->inlineScript()->captureEnd() ?>

现在我不确定如何将用户名/密码发送到 LoginController.php 并使用该模型从数据库表中验证用户名/密码。

任何示例或可能的解决方案都会很有帮助。

最佳答案

请不要将以下内容视为即用型解决方案。我还添加了更多部分,在您开始管理登录时您会发现它们很有用。您的主要部分应该是 Controller 的路由。除了其中的 ExtJS 部分,我还保留了 View 内容。不管怎样,我希望这对你有帮助。

首先是您的表单中存在一些问题。试试下面这个

var loginWindow;
Ext.onReady(function() {

    loginWindow = new Ext.create('Ext.window.Window',{
        title: 'Login',
        closable: false,
        draggable: false,
        resizable: false,
        width: 370,
        modal: true,
        items: [
            Ext.create('Ext.form.Panel', {
                id: 'LoginForm',
                bodyPadding: 5,
                width: 350, 
                layout: 'anchor',
                defaults: {
                    anchor: '100%'
                },
                defaultType: 'textfield',
                items: [{
                    fieldLabel: 'Username',
                    name: 'user',
                    allowBlank: false
                },{
                    fieldLabel: 'Password',
                    inputType: 'password',
                    name: 'pw',
                    allowBlank: false
                }],

                url: 'Login/Auth', // first one should be your controller, second one the controller action (this one need to accept post)
                buttons: [
                    {
                        text: 'Reset',
                        handler: function() {
                            this.up('form').getForm().reset();
                        }
                    },
                    {
                        text: 'Submit',
                        formBind: true,
                        disabled: true,
                        handler: function() {
                            var form = this.up('form').getForm();
                            if (form.isValid()) {
                                form.submit({
                                    success: function(form, action) {
                                       Ext.Msg.alert('Success', 'Authenticated!');
                                    },
                                    failure: function(form, action) {
                                        Ext.Msg.alert('Failed', 'Authentication Failed');
                                    }
                                });
                            }
                        }
                    }
                ]
            })
        ]
    }).show();
    // Ext.getBody().mask(); <- modal property does the same
});

现在到ZF2

路由

应用程序的每个页面都称为一个 Action , Action 被分组到模块内的 Controller 中。因此,您通常会将相关操作分组到一个 Controller 中。

URL 到特定操作的映射是使用模块的 module.config.php 文件中定义的路由完成的。您应该为登录操作添加一个路由。这是更新后的模块配置文件,在注释 block 中包含新代码。

<?php
return array(
    'controllers' => array(
        'invokables' => array(
            'Login\Controller\Login' => 'Login\Controller\LoginController',
        ),
    ),

    // The following section is new and should be added to your file
    'router' => array(
        'routes' => array(
            'login' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '/login[/:action][/:username][/:password]',
                    'constraints' => array(
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'username' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'password' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        'controller' => 'Login\Controller\Login',
                        'action'     => 'index',
                    ),
                ),
            ),
        ),
    ),

    'view_manager' => array(
        'template_path_stack' => array(
            'login' => __DIR__ . '/../view',
        ),
    ),
);

路由的名称是“login”,类型是“segment”。段路由允许您在 URL 模式(路由)中指定占位符,这些占位符将映射到匹配路由中的命名参数。在这种情况下,路由是 /login[/:action][/:id],它将匹配任何以/login 开头的 URL。下一个段将是一个可选的 Action 名称,最后下一个段将映射到一个可选的 id。方括号表示段是可选的。约束部分允许您确保段中的字符符合预期,因此您的操作仅限于以字母开头,随后的字符只能是字母数字、下划线或连字符。

Controller

现在您需要设置 Controller 。 Controller 是一个类,一般称为{Controller name}Controller。请注意,{Controller name} 必须以大写字母开头。此类位于模块的 Controller 目录中名为 {Controller name}Controller.php 的文件中。在您的情况下,它类似于 module/Login/src/Login/Controller。每个 Action 都是 Controller 类中名为 {action name}Action 的公共(public)方法。在您的情况下,{action name} 应该以小写字母开头。

<?php
namespace Login\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class LoginController extends AbstractActionController
{
    public function authenticateAction($username, $password)
    {
        $params = array('driver' => 'driver',
                        'dbname' => 'name');

        $db = new DbAdapter($params);

        use Zend\Authentication\Adapter\DbTable as AuthAdapter;
        // Oversimplified example without even hashing the password
        $adapter = new AuthAdapter($db,
                                   'Logins',
                                   'username',
                                   'password'
                                   );

        // get select object (by reference)
        $this->_adapter->setIdentity($username);
        $this->_adapter->setCredential($password);

        $result = $adapter->authenticate();

        if($result->isValid()) {
            // authenticated
        }
    }

    protected $loginTable;
    public function getLoginTable()
    {
        if (!$this->loginTable) {
            $sm = $this->getServiceLocator();
            $this->loginTable = $sm->get('Login\Model\LoginTable');
        }
        return $this->loginTable;
    }
}

View 脚本

这些文件将由 DefaultViewStrategy 执行,并将传递从 Controller 操作方法返回的任何变量或 View 模型。这些 View 脚本存储在我们模块的 View 目录中,该目录位于以 Controller 命名的目录中。现在创建这四个空文件:

module/Login/view/login/login/authenticate.phtml`

模型

module/Login/src/Login/Model 下创建一个名为 Login.php 的文件:

<?php
namespace Login\Model;

class Login
{
    public $id;
    public $username;
    public $password;

    public function exchangeArray($data)
    {
        $this->id     = (isset($data['id'])) ? $data['id'] : null;
        $this->username = (isset($data['username'])) ? $data['username'] : null;
        $this->password  = (isset($data['password'])) ? $data['password'] : null;
    }
}

module/Login/src/Login/Model 目录中创建您的 LoginTable.php 文件,如下所示:

<?php
namespace Login\Model;

use Zend\Db\TableGateway\TableGateway;

class LoginTable
{
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function getLogin($id)
    {
        $id  = (int) $id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function saveLogin(Login $login)
    {
        $data = array(
            'username' => $login->password,
            'password'  => $login->username,
        );

        $id = (int)$login->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getLogin($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Form id does not exist');
            }
        }
    }

    public function deleteLogin($id)
    {
        $this->tableGateway->delete(array('id' => $id));
    }
}

使用ServiceManager配置table gateway并注入(inject)LoginTable

将此方法添加到 module/LoginModule.php 文件的底部。

<?php
namespace Login;

// Add these import statements:
use Login\Model\Login;
use Login\Model\LoginTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;

class Module
{
    // getAutoloaderConfig() and getConfig() methods here

    // Add this method:
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'Login\Model\LoginTable' =>  function($sm) {
                    $tableGateway = $sm->get('LoginTableGateway');
                    $table = new LoginTable($tableGateway);
                    return $table;
                },
                'LoginTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new Login());
                    return new TableGateway('login', $dbAdapter, null, $resultSetPrototype);
                },
            ),
        );
    }
}

最后,您需要配置 ServiceManager 以便它知道如何获取 Zend\Db\Adapter\Adapter。 使用以下代码修改config/autoload/global.php

<?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',
        ),
    ),
);

您应该将您的数据库凭据放入config/autoload/local.php

<?php
return array(
    'db' => array(
        'username' => 'YOUR USERNAME HERE',
        'password' => 'YOUR PASSWORD HERE',
    ),
);

您可能还会发现以下代码片段很有用(查看测试演示):

https://github.com/zendframework/zf2

关于php - 使用 zend 模型和 Controller 实现登录认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13257592/

相关文章:

PHP : connecting to a Firebird (Interbase) database with Zend

PHP 下拉数据库代码不起作用?

php - SSL 错误无法更改为 TLS

php - 异常参数错误

extjs - 在 ExtJs 3.3.1 中,如何在不单击 EditorGrid 的情况下显示 ComboBox 下拉列表?

php - 我应该从 Zend_Db 移植到哪个 native mysql 类? (无 PDO 或 Mysqli)

javascript - php非登录情况下session超时如何避免?

json - Extjs 4 : Render store data into Ext. form.Panel不使用MVC框架

javascript - ExtJS 4 - 如果自定义验证失败,如何将表单字段标记为无效并在其周围显示红色边框(ExtJS 默认完成)?

php - Zend Framework 2 - 用于教义和注释表单的 Magic Getter 和 Setter