在Yii下建立工程并实现用户注册登陆
编辑工具:Netbeans,wampserver
数据库:MySQL
相应工程代码下载链接:Yii下用户注册登录系统
【下载Yii库,解压并使用命令建立工程】
以库文件在桌面并把工程sys建立在F盘的wamp/www文件夹下为例输入指令:
cd Desktop
cd yii/framework
yiic webapp F:wamp/www/sys
过程中如果出现‘’”php.exe”’不是内部或外部命令,也不是可运行的程序’的提示
解决方法:
打开yiic.bat,在set PHP_COMMAND后添加php的路径
修改path环境变量(把php.exe的路径设置到环境变量上去,在分号后面添加即可)
数据库
数据库代码:
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- 数据库: `sys`
--
-- --------------------------------------------------------
--
-- 表的结构 `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`userId` int(10) NOT NULL AUTO_INCREMENT,
`userName` varchar(64) CHARACTER SET utf8 NOT NULL,
`password` varchar(32) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=3 ;
工程文件结构
< protected / views / yiic.php >
修改$yiic的路径为框架文件的路径
< protected / index.php >
修改$yii的路径
< protected / config / main.php >
连接数据库,修改main.php中’db’的内容,如下
【views】
Yii的views目录下有layouts和 site 两个文件夹
< protected / views / layouts / main.php >
layouts中的main.php为页面主要框架,而site的内容显示在 $content
自行修改菜单
< protected / site >
< protected / views / site / Register.php >
<?php
$this->pageTitle=Yii::app()->name . ' - Register';
$this->breadcrumbs=array(
'Register',
);
?>
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'register-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
<?php
echo $form->errorSummary($model);
?>
<div class="row">
<?php echo $form->labelEx($model,'userName'); ?>
<?php echo $form->textField($model,'userName'); ?>
<?php echo $form->error($model,'userName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password'); ?> <!--渲染密码-->
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
< protected / views / site / Login.php >
<?php
/* @var $this SiteController */
/* @var $model LoginForm */
/* @var $form CActiveForm */
$this->pageTitle=Yii::app()->name . ' - Login';
$this->breadcrumbs=array(
'Login',
);
?>
<h1>Login</h1>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<div class="row">
<?php echo $form->labelEx($model,'userName'); ?>
<?php echo $form->textField($model,'userName'); ?>
<?php echo $form->error($model,'userName'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Login'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
【models】
Yii中的Model主要实现的功能为
(1)具备属性来存储数据
(2)public functions rules() 用来定义验证规则
(3)public function attributeLabels() 声明属性对于的标签名称
< protected / models / RegisterForm.php>
<?php
class RegisterForm extends CFormModel{
public $userName;
public $password;
public function rules(){
return array(
array('userName,password','required')
);
}
}
?>
< protected / models / LoginForm.php >
<?php
class LoginForm extends CFormModel
{
public $userName;
public $password;
private $_identity;
/**
* Declares the validation rules.
* The rules state that username and password are required,
* and password needs to be authenticated.
*/
public function rules()
{
return array(
// username and password are required
array('userName, password', 'required'),
// password needs to be authenticated
array('password', 'authenticate'),
);
}
/**
* Authenticates the password.
* This is the 'authenticate' validator as declared in rules().
*/
public function authenticate($attribute,$params)
{
if(!$this->hasErrors())
{
$this->_identity=new UserIdentity($this->userName,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','Incorrect username or password.');
}
}
/**
* Logs in the user using the given username and password in the model.
* @return boolean whether login is successful
*/
public function login()
{
if($this->_identity===null)
{
$this->_identity=new UserIdentity($this->userName,$this->password);
$this->_identity->authenticate();
}
if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
{
$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
Yii::app()->user->login($this->_identity,$duration);
return true;
} else {
return false;
}
}
}
【Controllers】
用户注册登录操作,主要为数据的查询、插入
< protected / controllers / SiteController.php >
<?php
class SiteController extends Controller
{
/**
* Declares class-based actions.
*/
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
// page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
'page'=>array(
'class'=>'CViewAction',
),
);
}
public function actionIndex(){
$this->render('index');
}
public function actionRegister(){
$model = new RegisterForm;
if(isset($_POST['RegisterForm'])){
$model->attributes=$_POST['RegisterForm'];
//不能写成"$userName = trim($model->userName);" or "$userName = isset($model->userName);"
$userName = $model->userName;
$password = md5($model->password);
$conn = Yii::app()->db;
$msql = "select userName from `user` where userName = '$userName' ";
$command = $conn->createCommand($msql);
$num = $command->queryRow(); //返回userName='$userName'那条记录
if($num){
$this->refresh();
} else {
$sql="insert into `user`(userName,password) values('$userName','$password')";
$command = $conn->createCommand($sql);
$dataReader = $command->query();
if($dataReader){
$this->redirect(Yii::app()->createUrl('/site/Login')); //控制器间跳转
exit();
}
}
$this->refresh();
}
$this->render('register',array('model'=>$model));
}
public function actionLogin(){
$model=new LoginForm;
if(isset($_POST['LoginForm'])){
$model->attributes = $_POST['LoginForm'];
$username = $model->userName;
$password = md5($model->password);
$conn = Yii::app()->db;
$sql = "select * from `user` where userName = '$username'";
$command = $conn->createCommand($sql);
$row = $command->queryAll(); //获取所有数据
foreach($row as $k => $v){ //获取到的数据为二维数组
$name = $v['userName'];
$pw = $v['password'];
}
if($name){
if($pw == $password){
Yii::app()->session['user'] = $name; //记录登录用户的session
$this->redirect(Yii::app()->createUrl('/site/content'));
} else {
echo "password is wrong";
$this->refresh();
}
} else{
echo "user is not exist";
$this->refresh(); //刷新页面
}
}
// display the login form
$this->render('login',array('model'=>$model));
}
public function actionContent(){
$model = new ContentForm;
if(isset($_POST['ContentForm'])){
$model->attributes = $_POST['ContentForm'];
$content = $model->content;
$conn = Yii::app()->db;
$sql = "insert into `user`(message)values('$content')";
$command = $conn->createCommand($sql);
$data = $command->query();
if($data){
$this->redirect(Yii::app()->createUrl('/site/index'));
}
}
$this->render('content',array('model'=>$model));
}
/**
* This is the action to handle external exceptions.
*/
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
}
?>
< protected / components >目录下的文件
< Controller.php >
<?php
class Controller extends CController
{
public $layout='//layouts/column1';
public $menu=array();
public $breadcrumbs=array();
}
?>
< UserIdentity.php >
<?php
class UserIdentity extends CUserIdentity
{
public function authenticate()
{
$users=array(
// username => password
'demo'=>'demo',
'admin'=>'admin',
);
if(!isset($users[$this->username]))
$this->errorCode=self::ERROR_USERNAME_INVALID;
elseif($users[$this->username]!==$this->password)
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
$this->errorCode=self::ERROR_NONE;
return !$this->errorCode;
}
}
?>
最终效果:
数据库数据:
备注:
以上项目在建立的时候,视图文件都在views/site上,当建立的是大工程的时候,工程文件就会变多,文件管理也会变得麻烦,而且,以上的文件结构也是不规范的,不符合MVC的文件结构,因此,可以参考以下工程文件结构
把相应的代码写到相应的控制器文件下,不过有两点需要注意:
(1)每个控制器下最好也写上actionError()函数,可以用于错误提示
(2)由于每个控制器名称和视图名称是对应的,当视图下的文件名称是什么,对应的控制器动作名称也要相同
例如:
controllers/RegisterController 的动作actionIndex() 和 views/register下的index.php 对应一致,否则会出现“The system is unable to find the requested action "index".” 的错误