注:本系列教程都在zend studio 6.1.1上开发完成,amp环境全部自己配置,以避免使用类似xampp\wamp等继承环境带来的未知问题。
1、首先创建存储用户的表
2、创建对应于数据库表的数据库访问模型,即Zend Table
在zend studio的工程上右键选择New Zend Framework Item,选择Zend Table,使用Users作为PHP文件名,以下是Users.php的内容:
代码具体的含义不言自明。
3、创建控制器
使用同2的方法创建Zend Framework Item,不过选择的是Zend Controller,使用AuthController.php作为PHP文件名。内容如下(控制器中使用的LoginForm 和RegistrationForm 是Zend_Form的子类,用于创建表单,细节在下一节):
<?php /** * AuthController * * @author happydagui.min * @version */ require_once 'Zend/Controller/Action.php'; require_once '../application/default/forms/LoginForm.php'; // 注意这里的路径的写法 require_once '../application/default/forms/RegistrationForm.php'; class AuthController extends Zend_Controller_Action { /** * The default action - show the home page */ public function homeAction() { // 进入首页前检查用户是否已经登录,否则转向登录页面 $storage = new Zend_Auth_Storage_Session ( ); $data = $storage->read (); if (! $data) { $this->_redirect ( 'auth/login' ); } $this->view->username = $data->username; } public function loginAction() { // 处理登录 $users = new Users ( ); $form = new LoginForm ( ); $this->view->form = $form; if ($this->getRequest ()->isPost ()) { if ($form->isValid ( $_POST )) { $data = $form->getValues (); $auth = Zend_Auth::getInstance (); $authAdapter = new Zend_Auth_Adapter_DbTable ( $users->getAdapter (), 'tb_users' ); $authAdapter->setIdentityColumn ( 'username' ) ->setCredentialColumn ( 'password' ); $authAdapter->setIdentity ( $data ['username'] ) ->setCredential ( $data ['password'] ); $result = $auth->authenticate ( $authAdapter ); if ($result->isValid ()) { $storage = new Zend_Auth_Storage_Session ( ); $storage->write ( $authAdapter->getResultRowObject () ); $this->_redirect ( 'auth/home' ); } else { $this->view->errorMessage = "Invalid username or password, Please try again."; } } } } public function signupAction() { // 处理注册 $users = new Users ( ); $form = new RegistrationForm ( ); $this->view->form = $form; if ($this->getRequest ()->isPost ()) { if ($form->isValid ( $_POST )) { $data = $form->getValues (); if ($data ['password'] != $data ['confirmPassword']) { $this->view->errorMessage = "Password and confirm password donnot match."; return; } if ($users->checkUnique ( $data ['username'] )) { $this->view->errorMessage = "Name already taken."; return; } unset ( $data ['confirmPassword'] ); $users->insert ( $data ); $this->_redirect ( 'auth/login' ); } } } public function logoutAction() { // 处理注销 $storage = new Zend_Auth_Storage_Session ( ); $storage->clear (); $this->_redirect ( 'auth/login' ); } }
// 这里去掉了php的结束符号 4、显示注册和登录的表单类,需要手工创建LoginForm.php(位置:application/default/forms/)
RegistrationForm.php(位置:application/default/forms/)
5、创建完控制器和表单后,下一步自然是视图
home.phtml
login.phtml文件
signup.phtml文件
如有什么问题,请提出来探讨。我这里完全可以运行。
另外,可以考虑抽象控制器的一个基类,来实现统一的验证。这个后续再将。
转载于:https://blog.51cto.com/happydagui2222/145088