Zendframework登陸註冊實例教程

一.服務器配置

說明:這個實例的開發系統環境是windows 7,所用服務器是Nginx1.0.5Zendframework框架的版本是1.11.9PHP5.3.6,所用數據庫是MySQL 5.1.50

首先從配置Nginx開始,在這裏面需要開啓URLrewrite

這個是我的nginx.conf文件中配置虛擬主機部分

文件:D:\nginx\nginx-1.0.5\conf\nginx.conf

location ~ \.php$ {

            root           html;

            fastcgi_pass   127.0.0.1:9000;

 

             #如果是一個文件夾,訪問規則301

             if (-d $request_filename){

                 rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;

             }

 

             #如果沒有改文件訪問默認文件

             if (!-e $request_filename) {

                    rewrite ^/(.*)$ /myproject/index.php last;

         }

 

             #自動在訪問URL後面加"/"

             if (-d $request_filename){

                   rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;

             }

 

            fastcgi_index  index.php;

            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;

             fastcgi_param PATH_INFO $fastcgi_script_name;

           

             include        fastcgi_params;

二.建立項目

然後在你的Nginxhtml目錄下建立如下文件

myproject/

/application

/controllers

/models

/views

/filters

/helpers

/scripts

/library

/public

/images

/scripts

/styles

 

Zend Framework 的控制器,Zend_Controller,被設計支持使用clean urls 的網站。爲實現這個目的,所有的請求需要通過單一的index.php 文件,這就是所知的啓動文件(bootstrapper)。這給我們提供了程序中所有頁面的中心點並確保運行環境配置正確。我們

.htaccess 文件來實現這個目的,.htaccess myproject 的根目錄中,內容如下:

文件:myproject/.htaccess

 

RewriteEngine on

RewriteCond %{SCRIPT_FILENAME} !-f

RewriteCond %{SCRIPT_FILENAME} !-d

RewriteRule ^(.*)$ index.php/$1

RewriteRule 非常簡單並可以翻譯爲“對任何url, 重定向到index.php”。

然而,對於圖像,JavaScript CSS 文件的請求不應該重定向到啓動文件,把這些文件放到public 目錄下myproject/public 下:

文件:myproject/public/.htaccess

RewriteEngine off

雖然我們當前的rewrite rules 不需要太嚴格,但我們還是在application library 目錄下添加一些.htaccess 文件用來保護我們的程序:

文件:myproject/application/.htaccess

deny from all

文件:myproject/library/.htaccess

deny from all

三.網站

啓動文件

接下來我們開始正式開始這個項目,首先是啓動文件,也就是放在myproject根目錄下的index.php它是個跳轉的文件,在裏面告訴請求執行那些操作。

文件myproject/index.php

<?php

error_reporting ( E_ALL | E_STRICT );

date_default_timezone_set ( 'Europe/London' );

set_include_path ( '.' . PATH_SEPARATOR . './library' . PATH_SEPARATOR . './application/models/' . PATH_SEPARATOR . get_include_path () );

 

include "Zend/Loader.php";

Zend_Loader::loadClass ( 'Zend_Controller_Front' );

Zend_Loader::loadClass ( 'Zend_Config_Ini' );

Zend_Loader::loadClass ( 'Zend_Registry' );

Zend_Loader::loadClass ( 'Zend_Db' );

Zend_Loader::loadClass ( 'Zend_Db_Table' );

Zend_Loader::loadClass ( 'Zend_Auth' );

Zend_Loader::loadClass ( 'Zend_Auth_Adapter_DbTable' );

 

$config = new Zend_Config_Ini ( './application/config.ini', 'general' );

$registry = Zend_Registry::getInstance ();

$registry->set ( 'config', $config );

 

$db = Zend_Db::factory ( $config->db->adapter, $config->db->config->toArray () );

Zend_Db_Table::setDefaultAdapter ( $db );

 

$frontController = Zend_Controller_Front::getInstance ();

$frontController->throwExceptions ( true );

$frontController->setBaseUrl ( '/login' );

$frontController->setControllerDirectory ( './application/controllers' );

 

 

// run!

$frontController->dispatch ();

 

注意我們沒有在文件的結尾放?>,因爲它不是必須的並且有個好處是:我們可以防止當多餘的whitespace 發生在?>後面出現難以調試的錯誤。

 

創建模型(M)

做這個例子需要建立一個用戶信息的數據庫,之後在mysql裏建立一個數據庫,裏面需要有如下數據,一個數據表user

裏面含有三個字段id,username,password

然後我們在models裏面建立自己的模型:

文件:myproject/application/models/user.php

 

<?php

class User extends Zend_Db_Table {

    

     protected $_id;

     protected $_username;

     protected $_password;

    

     public function checkUnique($username) {

              //註冊驗證用戶米是否存在

              $select = $this->_db->select ()->from ('user')->where ( 'username = ?', $username );

              $result = $this->getAdapter ()->fetchOne ( $select );

             

              if ($result) {

                       return true;

              } else {

                       return false;

              }

     }

}

 

連接數據庫需要有配置文件,Zend Framework 提供了一個Zend_Config 來提供靈活的面向對象訪問配置文件。此刻,配置

文件可以是一個PHP 數組,一個INI 文件或者XML 文件。我們將使用INI 文件:

文件:myproject/application/config.ini

[general]

db.adapter = PDO_MYSQL

db.config.host = localhost

db.config.username = root

db.config.password = 123456

db.config.dbname = login

創建試圖文件(V)

使用Zend studio創建視圖文件可以在Zend studio裏面右鍵項目—newàotherà會彈出下面頁面,建立視圖文件。

 

有了控制器可以開始寫我們的視圖文件了,基於MVC模式寫的Zendframework的視圖文件擴展名是.phtml

文件:myproject\application\views\scripts\index.phtml

<?php echo $this->render('header.phtml'); ?>

<h1><?php echo $this->escape($this->title); ?></h1>

<form name = "form1" action="index/login" method="post">

用戶名:<input type="text" id="username"  name="username"/> <br/>     

密碼:<input type="password" id="password"  name="password"/> <br/>

<?php echo $this->username;?>

<input type="submit" name="submit" value="登陸">

</form>

<a href="/register/index">還沒有賬號,點此註冊</a>

<div style="display:none;">

<table>

測試用戶名和密碼,用於查看數據庫是否連接成功

<?php foreach($this->user as $u) : ?>

<tr>

<td><?php echo $this->escape($u->username);?></td>

<td><?php echo $this->escape($u->password);?></td>

<td>

</td>

</tr>

<?php endforeach; ?>

</table>

</div>

 

<?php echo $this->render('footer.phtml'); ?>

 

其中考慮到代碼的公共部分可以重複使用,在視圖裏加了頭部和腳部的文件。

文件:myproject/application/views/scripts/header.phtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

Page 9 of 18

<title><?php echo $this->escape($this->title); ?></title>

</head>

<body>

<div id="content">

 

文件:myproject/application/views/scripts/footer.phtml

</div>

</body>

</html>

設置控制器(C)

 

Zend studio裏面右鍵項目—newàotherà會彈出下面頁面,建立控制器。

 

 

 

假如我們把這個網站的首頁設爲登錄界面,則在設置的默認控制器爲

文件:myproject/application/controllers/IndexController.php

<?php

 

 

 

require_once 'Zend/Controller/Action.php';

 

class RegisterController extends Zend_Controller_Action {

        

         function init() {

                   $this->initView ();

                   $this->view->baseUrl = $this->_request->getBaseUrl ();

                   Zend_Loader::loadClass ( 'User' );

         }

        

         public function indexAction() {

                  

                   if ($this->getRequest ()->isPost ()) {

                            $username = $this->_request->get ( "username" );

                            //echo $username;

                            $password = $this->_request->get ( "password" );

                            $pwd = 'w' . $password;

                            $pwd = md5 ( $pwd );

                            echo $pwd;

                            $user = new User ();

                            $auth = Zend_Auth::getInstance ();

                           

                            if ($user->checkUnique ( $username )) {

                                     echo "用戶名已經存在!";

                            } else {

                                     $data = array ('username' => $username, 'password' => $pwd );

                                    

                                     $user->insert ( $data );

                                     $this->_redirect ( '/register/success' );

                           

                            }

                  

                   } else {

                            $this->view->title = "歡迎註冊";

                            $this->render ();

                   }

        

         }

        

         function logoutAction() {

                   // 處理註銷

                   $storage = new Zend_Auth_Storage_Session ();

                   $storage->clear ();

                   $this->_redirect ( '/index/index' );

         }

        

         function successAction() {

                   // 註冊成功

         }

 

}

 

好了,現在在瀏覽器裏輸入你的URL就可以看到如下界面了,如果想要測試數據庫連接可以把上面代碼中的<div style="display:none;">style去掉。

URL: http://127.0.0.1/myproject

 

 

接下來我們來處理登錄表單發送的POST請求,在action裏面寫了它的controlleraction的名字在上面的代碼中我們已經給出了,這裏只做簡單的說明:後臺Indexaction通過接收前臺發送的usernamepassword盡心加密處理,只裏面問了增加安全界別,我們在密碼前面加了一個字符再用md5()函數進行加密,然後通過框架中自帶的類

Zend_Auth_Adapter_DbTable中的方法進行密碼比較。然後是邏輯判斷之後我們會增加登錄成功的頁面和出錯的頁面:

文件:myproject\application\views\scripts\index\login.phtml

<?php

echo "<h1>恭喜你登陸成功!</h1>";

 

文件:myproject\application\views\scripts\index\error.phtml

<?php

echo "用戶名或者密碼錯誤!";

 

以及一些CSS的文件:

文件:myproject /public/styles/site.css

body,html {

font-size:100%;

margin: 0;

font-family: Verdana,Arial,Helvetica,sans-serif;

color: #000;

background-color: #fff;

}

h1 {

font-size:1.4em;

color: #800000;

background-color: transparent;

}

#content {

width: 770px;

margin: 0 auto;

}

label {

width: 100px;

display: block;

float: left;

}

#formbutton {

margin-left: 100px;

}

a {

color: #800000;

}

 

有了登錄的例子我們可以繼續寫註冊了其實原理都一樣,只不過使用的SQL語句有差別而已,我們還是先建立控制器controller和視圖view文件吧.

 

註冊功能的視圖文件:

 

文件:myproject\application\views\scripts\register\index.phtml

<?php echo $this->render('header.phtml'); ?>

<h1><?php echo $this->escape($this->title); ?></h1>

 

<form name = "form1" action="/register/index" method="post">

用戶名:<input type="text" id="username"  name="username"/> <br/>     

密碼:<input type="password" id="password"  name="password"/> <br/>

 

<?php echo $this->username;?>

<input type="submit" name="submit" value="註冊"/>

</form>

<a href="/index/index">已有賬號,點此登錄</a>

 

<?php echo $this->render('footer.phtml'); ?>

 

文件:myproject\application\views\scripts\register\success.phtml

<?php

echo "註冊成功!";

?>

<a href="/index/index">

<h1>點此登錄</h1>

</a>

註冊功能的控制器文件:

文件:myproject/application/controllers/RegisterController.php

<?php

 

 

 

require_once 'Zend/Controller/Action.php';

 

class RegisterController extends Zend_Controller_Action {

    

     function init() {

              $this->initView ();

              $this->view->baseUrl = $this->_request->getBaseUrl ();

              Zend_Loader::loadClass ( 'User' );

     }

    

     public function indexAction() {

             

              if ($this->getRequest ()->isPost ()) {

                       $username = $this->_request->get ( "username" );

                       //echo $username;

                       $password = $this->_request->get ( "password" );

                       $pwd = 'w' . $password;

                       $pwd = md5 ( $pwd );

                       echo $pwd;

                       $user = new User ();

                       $auth = Zend_Auth::getInstance ();

                      

                       if ($user->checkUnique ( $username )) {

                                 echo "用戶名已經存在!";

                       } else {

                                 $data = array ('username' => $username, 'password' => $pwd );

                                

                                 $user->insert ( $data );

                                 $this->_redirect ( '/register/success' );

                      

                       }

             

              } else {

                       $this->view->title = "歡迎註冊";

                       $this->render ();

              }

    

     }

     function successAction() {

              // 註冊成功

     }

}

 

在創建模型文件的時候可能會有checkUnique()函數有所困惑,現在可以明確了,在註冊的控制器裏用到的。當用戶填寫表單數據發送到後臺之後檢測用戶名是否存在,不存在時候可以在數據表中插入一條數據,注意一定是以數組形式插入。

最後看一下這個網站的目錄結構了:

myproject/

/application

/controllers

         /IndexController.php

         /RegisterController.php

/models

         /User.php

/views

/filters

/helpers

/scripts

         /index

                  /index.phtml

                  /Login.phtml

                  /error.phtml

/register

         /index.phtml

         /success.hhtml

/footer.phtml

/header.phtml

                            /.htaccess

                            /config.ini

/library

              /Zend…(此處省略一萬字…)

              /.htaccess

/public

/images

/scripts

/styles

         /site.css

/.htaccess

/.htacccess

發佈了51 篇原創文章 · 獲贊 14 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章