最近打開我以前做的一個項目,系統結構中使用了4個包含文件對登錄用戶的權限進行判斷,屬典型的面向過程寫法,可能很多朋友以前都寫過這樣的代碼。我把這些代碼整理了一下,寫成一個權限判斷的簡單類,以比較一個面各對象和面向過程之間的差異。 代碼如下(其中省略了部分代碼)。
sesson1.php <?php /* * 功能:取得用戶的cookie,以判斷用戶是否已經登錄,并是否具有系統管理員權限 * 程序員:xiangli * 日期:2002-07-19 */
$UserName = $HTTP_COOKIE_VARS['UserName1'];//用戶名 if ( empty($UserName) || $HTTP_COOKIE_VARS['Level'] != 1 ) { header("Location: ../right.phtml"); } ?>
session2.php <?php /* * 功能:取得用戶的cookie,以判斷用戶是否已經登錄,并是否具有操作員權限 * 程序員:xiangli * 日期:2001-07-19 */
$UserName = $HTTP_COOKIE_VARS['UserName1'];//用戶名 $Level = $HTTP_COOKIE_VARS['Level'];//權限級別
if ( empty($UserName) || $Level > 2 ) { header("Location: ../index.phtml"); } ?>
session3.php <?php /* * 功能:取得用戶的cookie,以判斷用戶是否已經登錄,用戶是否具有普通用戶權限 * 程序員:xiangli * 日期:2001-07-19 */
if ( empty($UserName1) || $Level > 3 ) { header("Location: ./right.phtml"); } ?>
session4.php <?php /* * 功能:取得用戶的cookie,以判斷用戶是否已經登錄,用戶是否具有企業用戶權限 * 程序員:xiangli * 日期:2001-08-11 */
if ( empty($_COOKIE['ClientName']) || $_COOKIE['Level'] != 4 ) { #header("Location: ../client_login.phtml"); } ?>
調用: <? include_once("/lib/session1.php"); include_once("/lib/session2.php"); include_once("/lib/session3.php"); include_once("/lib/session4.php"); ?>
合并后的權限判斷類: sessionPower.php <?php /** * @功能:根據cookie的值判斷用戶是否已經登錄及用戶的權限 * @程序員:xiangli * @日期:2002-12-20 */
class sessionPower{ var Username;//用戶名 var Level;//用戶權力級別
/** * 判斷用戶是否已經登錄 */ function sessionPower() { $this->UserName = $HTTP_COOKIE_VARS['UserName'];//用戶名 $this->Level = $HTTP_COOKIE_VARS['Level'];//權限級別
if ( $this->UserName == "" || $this->Level == "" ) { header("Location: ../index.phtml"); } }
/** * 是否具有系統管理員權限 */ function adminPower() { if ( $HTTP_COOKIE_VARS['Level'] != 1 ) { header("Location: ../right.phtml"); } }
/** * 是否具有操作員權限 */ function operatorPower() { if ( $this->Level > 2 ) { header("Location: ../index.phtml"); } }
/** * 是否具有普通用戶權限 */ function generalPower() { if ( $this->Level > 3 ) { header("Location: ./right.phtml"); } }
/** * 用戶是否具有企業用戶權限 */ function enterprisePower() { if ( $this->Level != 4 ) { #header("Location: ../client_login.phtml"); } } } ?>
調用: <? include_once("/lib/sessionPower.php"); $sessionPower = new sessionPower(); $sessionPower->adminPower(); $sessionPower->operatorPower(); $sessionPower->generalPower(); $sessionPower->enterprisePower(); ?>
注:如果使用面向對象編程,建議最好使用zend編輯器,這樣開發效率會快出很多!
|