search

前言

第一次接触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   .   " " ;
         $xml   =   $xml   .   " " ;
         $xml   =   $xml   .   " "   .   $guidID   .   " " ;
         $xml   =   $xml   .   " " ;
         $xml   =   $xml   .   " " ;
         $xml   =   $xml   .   " "   .   $result   .   " " ;
         $xml   =   $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   .   " " . $row [ " etn " ] . " " ;
                         $etn   =   $etn   .   " " . $row [ " grp_id " ] . " " ;
                         $etn   =   $etn   .   " " . $row [ " email " ] . " " ;
                         $etn   =   $etn   .   " " . $row [ " nm " ] . " " ;
                         $etn   =   $etn   .   " " ;
                         $etn   =   $etn   .   " " . $row [ " state " ] . " " ;
                         $etn   =   $etn   .   " " . $row [ " reg_time " ] . " " ;
                         $etn   =   $etn   .   "
" ;
                    }
                }
            }
             catch ( Exception   $e )
            {
                 //
            }
        }
        
         $xml   =   " " ;
         $xml   =   $xml   .   " " ;
         $xml   =   $xml   .   " " ;
         $xml   =   $xml   .   " "   .   $guidID   .   " " ;
         $xml   =   $xml   .   " " ;
         $xml   =   $xml   .   " " . $etn . " " ;
         $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 ;
        }
    }
}

?>


 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools