使用zend模型和控制器实现登录验证

Mic*_*eal 2 php extjs zend-db zend-framework2

我使用的是Zend 2.0,我从未将EXTJS与Zend结合使用.

这是我在视图/ 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() ?>
Run Code Online (Sandbox Code Playgroud)

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

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

sra*_*sra 6

请不要将以下内容视为即用型解决方案.我还添加了一些您在开始管理登录时会发现有用的部分.您的主要部分应该是控制器的路由.除了ExtJS部分之外,我还保留了视图内容.无论如何,我希望这会对你有所帮助.

首先是表格中的一些问题.尝试以下方法

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
});
Run Code Online (Sandbox Code Playgroud)

现在到ZF2

路由

应用程序的每个页面都称为操作,操作被分组到模块中的控制器中.因此,您通常会将相关操作分组到控制器中.

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

<?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',
        ),
    ),
);
Run Code Online (Sandbox Code Playgroud)

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

控制器

现在您需要设置控制器.控制器是一个通常称为{Controller name} Controller的类.请注意,{Controller name}必须以大写字母开头.此类位于模块的Controller目录中名为{Controller name} Controller.php的文件中.在你的情况下,这将是模块/登录/ src /登录/控制器.每个操作都是控制器类中的一个名为{action name} Action的公共方法.在你的情况下,{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;
    }
}
Run Code Online (Sandbox Code Playgroud)

视图脚本

这些文件将由DefaultViewStrategy执行,并将传递从控制器操作方法返回的任何变量或视图模型.这些视图脚本存储在我们模块的views目录中,该目录位于以控制器命名的目录中.立即创建这四个空文件:

模块/登录/视图/登录/登录/ 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

使用ServiceManager配置表网关并注入LoginTable

将此方法添加到module/Login中Module.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);
                },
            ),
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,您需要配置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',
        ),
    ),
);
Run Code Online (Sandbox Code Playgroud)

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

<?php
return array(
    'db' => array(
        'username' => 'YOUR USERNAME HERE',
        'password' => 'YOUR PASSWORD HERE',
    ),
);
Run Code Online (Sandbox Code Playgroud)

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

https://github.com/zendframework/zf2