My First Time For PHP
前言
第一次接触PHP,功能需求很简单:负责提供WEB接口,接收数据,然后与数据库交互,最终响应XML结果。过程中接触了PHP的很多常用语法和功能,比如PDO对数据库的操作、XML操作、面向对象、正则表达式、输出输出......等等。基本是上网搜索示例,然后自己摸索着写代码,因为N年来一直写的是.Net,所以项目过程中受到.Net很大影响,用了三层构架,甚至为每个PHP接口写了一个类似CodeBehind的Class,没有时间了解PHP下的开发框架,完全按自己的想法搭建的项目。在此篇随笔记录,以便以后备忘查询,也希望得到PHP专业人士的指点。
DAL
原本是想封装个DBUtility的类,但几天时间无法对PDO了解的全面和应用自如,只得把数据库相关操作混合在DAL中。
代码
php
/* ***********************************************************
DAL
wujian 2010-01-19
*********************************************************** */
define ( " DB_BASIC " , " mysql:host=localhost;dbname=asterisk " );
define ( " DB_USER " , " root " );
define ( " DB_PSWD " , " root " );
class DAL
{
private static $pdo ;
// 构造函数
public function __construct()
{
//
}
// 判断分组是否存在
public function GroupExist( $grpid )
{
$this -> pdo = new PDO(DB_BASIC , DB_USER , DB_PSWD);
$cmd = " SELECT COUNT(*) FROM extension_group WHERE `grp_id` = " . $grpid ;
$rs = $this -> pdo -> query( $cmd );
$arr = $rs -> fetchAll();
$this -> pdo = null ;
if ( $arr [ 0 ][ 0 ] == 1 )
{
return true ;
}
else
{
return false ;
}
}
// 判断分机是否存在
public function ExtensionExist( $etn )
{
$this -> pdo = new PDO(DB_BASIC , DB_USER , DB_PSWD);
$cmd = " SELECT COUNT(*) FROM extension_email WHERE `etn` = ' " . $etn . " ' " ;
$rs = $this -> pdo -> query( $cmd );
$arr = $rs -> fetchAll();
$this -> pdo = null ;
if ( $arr [ 0 ][ 0 ] == 1 )
{
return true ;
}
else
{
return false ;
}
}
// 添加分机(分机号,分组ID,EMAIL,名称,备注)
public function ExtensionAdd( $etn , $grpid , $email , $name , $desc )
{
/* prepare方式
$stmt = $this->pdo->prepare("INSERT INTO extensionemail (`etn`, `grp_id`, `email`, `nm`, `desc`) VALUES (:a, :b, :c, :d, :e)");
$stmt->bindParam(':a', $etn);
$stmt->bindParam(':b', $grpid);
$stmt->bindParam(':c', $email);
$stmt->bindParam(':d', $name);
$stmt->bindParam(':e', $desc);
$stmt->execute();
*/
/* exec方式 */
$this -> pdo = new PDO(DB_BASIC , DB_USER , DB_PSWD);
$cmd = " INSERT INTO extension_email (`etn`, `grp_id`, `email`, `nm`, `desc`) VALUES (' " . $etn . " ', " . $grpid . " , ' " . $email . " ', ' " . $name . " ', ' " . $desc . " ') " ;
$s = $this -> pdo -> exec ( $cmd );
$this -> pdo = null ;
if ( $s == 1 ){
return true ;
}
else {
return false ;
}
}
// 更新分机(分机号,分组ID,EMAIL,名称,备注)
public function ExtensionEdit( $etn , $grpid , $email , $name , $desc )
{
$this -> pdo = new PDO(DB_BASIC , DB_USER , DB_PSWD);
$cmd = " UPDATE extension_email SET `grp_id` = " . $grpid . " , `email` = ' " . $email . " ', `nm` = ' " . $name . " ', `desc` = ' " . $desc . " ' WHERE `etn` = " . $etn ;
$s = $this -> pdo -> exec ( $cmd );
$this -> pdo = null ;
if ( $s == 1 ){
return true ;
}
else {
return false ;
}
}
// 激活分机
public function ExtensionAct( $etn , $state )
{
$this -> pdo = new PDO(DB_BASIC , DB_USER , DB_PSWD);
$cmd = " UPDATE extension_email SET `state` = " . $state . " , `reg_time` = CURRENT_TIMESTAMP() WHERE `etn` = " . $etn ;
$s = $this -> pdo -> exec ( $cmd );
$this -> pdo = null ;
if ( $s == 1 ){
return true ;
}
else {
return false ;
}
}
// 分机列表
public function ExtensionList( $grpid )
{
$this -> pdo = new PDO(DB_BASIC , DB_USER , DB_PSWD);
$cmd = " SELECT * FROM extension_email WHERE `grp_id` = " . $grpid ;
if ( $grpid == 0 )
{
$cmd = " SELECT * FROM extension_email " ;
}
$rs = $this -> pdo -> query( $cmd );
$arr = $rs -> fetchAll();
$this -> pdo = null ;
return $arr ;
}
// 分组列表
public function GroupList()
{
$this -> pdo = new PDO(DB_BASIC , DB_USER , DB_PSWD);
$cmd = " SELECT * FROM extension_group " ;
$rs = $this -> pdo -> query( $cmd );
$arr = $rs -> fetchAll();
$this -> pdo = null ;
return $arr ;
}
}
?>
BLL
业务层调用DAL,并为UI提供服务
代码
php
/* ***********************************************************
BLL
吴剑 2010-01-19
*********************************************************** */
require " dal.php " ;
class BLL
{
private static $myDAL ;
// 构造函数
public function __construct()
{
$this -> myDAL = new DAL();
}
// 判断分组是否存在
public function GroupExist( $grpid )
{
return $this -> myDAL -> GroupExist( $grpid );
}
// 判断分机是否存在
public function ExtensionExist( $etn )
{
return $this -> myDAL -> ExtensionExist( $etn );
}
// 添加分机(分机号,EMAIL,名称,备注)
public function ExtensionAdd( $etn , $grpid , $email , $name , $desc )
{
return $this -> myDAL -> ExtensionAdd( $etn , $grpid , $email , $name , $desc );
}
// 更新分机(分机号,分组ID,EMAIL,名称,备注)
public function ExtensionEdit( $etn , $grpid , $email , $name , $desc )
{
return $this -> myDAL -> ExtensionEdit( $etn , $grpid , $email , $name , $desc );
}
// 激活分机
public function ExtensionAct( $etn , $state )
{
return $this -> myDAL -> ExtensionAct( $etn , $state );
}
// 分机列表
public function ExtensionList( $grpid )
{
return $this -> myDAL -> ExtensionList( $grpid );
}
// 分组列表
public function GroupList()
{
return $this -> myDAL -> GroupList();
}
}
?>
UI
虽然在PHP中用类似CodeBehind的方式没有事件与页面控件的关联,没有Class与Page间的对象继承关系,但还是觉得这样分离逻辑会更清晰,也许长期用.Net的惯性思维,不喜欢将逻辑代码嵌套在页面中。
extension_add.php
php
require " extension_add.class.php " ;
?>
extension_edit.class.php
代码
php
/* ***********************************************************
添加分机
吴剑 2010-01-19
*********************************************************** */
// 加载公共类
require " class/common.php " ;
// 加载业务类
require " class/bll.php " ;
define ( " AUTH_KEY " , " test " );
class ExtensionAdd
{
// 页面初始化
static function pageLoad()
{
$guidID = "" ;
// 0:成功 1:密钥无效 2:提交数据格式有误 3:分机号已存在 4:分组不存在 9:接口异常
$result = 9 ;
if ( isset ( $_POST [ " data " ]))
{
try
{
$doc = new DOMDocument();
$doc -> loadXML( $_POST [ " data " ]);
$root = simplexml_import_dom ( $doc );
$the_authKey = $root -> head -> authKey;
$the_guidID = $root -> head -> guidID;
$the_extension = $root -> body -> extension;
$the_groupID = $root -> body -> groupID;
$the_email = $root -> body -> email;
$the_name = $root -> body -> name;
$the_desc = $root -> body -> desc;
$guidID = $the_guidID ;
// 数据格式验证
if (Common :: IsExtension( $the_extension ) && Common :: IsInt( $the_groupID ) && Common :: IsEmail( $the_email ))
{
// 密钥验证
if ( $the_authKey == AUTH_KEY)
{
// 创建业务对象
$myBLL = new BLL();
// 分机是否存在
if ( $myBLL -> ExtensionExist( $the_extension ))
{
$result = 3 ;
}
else
{
// 分组是否存在
if ( $myBLL -> GroupExist( $the_groupID ))
{
if ( $myBLL -> ExtensionAdd( $the_extension , $the_groupID , $the_email , $the_name , $the_desc ))
{
$result = 0 ;
}
}
else
{
$result = 4 ;
}
}
}
else
{
// 密钥无效
$result = 1 ;
}
}
else
{
// 数据格式有误
$result = 2 ;
}
}
catch ( Exception $e )
{
// 数据格式有误
$result = 2 ;
}
}
else
{
// 提交数据格式有误
$result = 2 ;
}
$xml = " " ;
$xml = $xml . " " ;
// 指定页面编码
header ( " content-type:text/xml; charset=utf-8 " );
echo ( $xml );
}
}
ExtensionAdd :: pageLoad();
?>
extension_list.class.php
代码
php
/* ***********************************************************
分机列表
吴剑 2010-01-19
*********************************************************** */
// 加载业务类
require " class/bll.php " ;
define ( " AUTH_KEY " , " test " );
class ExtensionList
{
// 页面初始化
static function pageLoad()
{
$guidID = "" ;
// 0:成功 1:密钥无效 2:提交数据格式有误 3:分机号已存在 4:分组不存在 9:接口异常
$etn = "" ;
if ( isset ( $_POST [ " data " ]))
{
try
{
$doc = new DOMDocument();
$doc -> loadXML( $_POST [ " data " ]);
$root = simplexml_import_dom ( $doc );
$the_authKey = $root -> head -> authKey;
$the_guidID = $root -> head -> guidID;
$the_groupID = $root -> body -> groupID;
$guidID = $the_guidID ;
// 密钥验证
if ( $the_authKey == AUTH_KEY)
{
// 创建业务对象
$myBLL = new BLL();
$arr = $myBLL -> ExtensionList( $the_groupID );
foreach ( $arr as $row )
{
$etn = $etn . "
$etn = $etn . "
$etn = $etn . "
$etn = $etn . "
$etn = $etn . "
$etn = $etn . "
$etn = $etn . "
$etn = $etn . "
$etn = $etn . "
}
}
}
catch ( Exception $e )
{
//
}
}
$xml = " " ;
$xml = $xml . " " ;
// 指定页面编码
header ( " content-type:text/xml; charset=utf-8 " );
echo ( $xml );
}
}
ExtensionList :: pageLoad();
?>
Common
主要应用了正则表达式
代码
php
/* ***********************************************************
公共
吴剑 2010-01-19
*********************************************************** */
class Common
{
// 非空验证
static function IsNon( $str )
{
return true ;
}
// 正整数验证
static function IsInt( $str )
{
$reg = " ^[0-9]+$ " ;
if ( ereg ( $reg , $str ))
{
return true ;
}
else
{
return false ;
}
}
// 分机号格式验证
static function IsExtension( $str )
{
$reg = " ^[0-9]+$ " ;
if ( ereg ( $reg , $str ))
{
return true ;
}
else
{
return false ;
}
}
// Email格式验证
static function IsEmail( $str )
{
$reg = " ^([_a-zA-Z0-9+\.]+@([_a-zA-Z0-9]+\.)+[a-zA-Z0-9]{2,4})?$ " ;
if ( ereg ( $reg , $str ))
{
return true ;
}
else
{
return false ;
}
}
}
?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.
