Table of Contents
搭建自己的PHP框架(三),搭建php框架
重写异常类
注册全局异常方法
其他全局函数
Home php教程 php手册 搭建自己的PHP框架(三),搭建php框架

搭建自己的PHP框架(三),搭建php框架

Jul 06, 2016 pm 02:24 PM
php three main build frame my own

搭建自己的PHP框架(三),搭建php框架

续言

接着完善自己的PHP框架,本次更新的主要内容有:

  • 介绍了异常处理机制
  • 完善了异常和错误处理
  • 数据表跟Model类的映射

异常处理
<p>异常处理:异常处理是编程语言或计算机硬件里的一种机制,用于处理软件或信息系统中出现的异常状况(即超出程序正常执行流程的某些特殊条件)</p>
Copy after login

异常处理用于处理程序中的异常状况,虽说是“异常状态”,但仍然还是在程序编写人员的预料之中,其实程序的异常处理完全可以用‘if else’语句来代替,但异常处理自然有其优势之处。

个人总结其优点如下:

  • 可以快速终止流程,重置系统状态,清理变量和内存占用,在普通WEB应用中,一次请求结束后,FAST CGI会自动清理变量和上下文,但如果在PHP的命令行模式执行守护脚本时,它的效果就会很方便了。
  • 大量的if else语句会使代码变得繁杂难懂,使用异常处理可以使程序逻辑更清晰易懂,毕竟处理异常的入口只有catch语句一处。
  • 一量程序中的函数出现异常结果或状况,如果使用函数的return方式返回异常信息,层层向上,每一次都要进行return判断。使用异常处理我们可以假设所有的返回信息都是正常的,避免了大量的代码重复。

虽然将代码放在try catch块中会有微微的效率差,但是跟这些优点一比,这点消耗就不算什么了。那么PHP的异常处理怎么使用呢?

PHP内置有Exception类,使得我们可以通过实例化异常类来抛出异常。我们将代码放在try语句中执行,并在其后用catch试图捕捉到在try代码块中抛出的异常,并对异常进行处理。我们还可以在catch代码段后使用finally语句块,无论是否有异常都会执行finally代码块的代码,try catch语句形如下面代码:

<code class="none">try{
    throw new Exeption('msg'[,'code',$previous_exeception]);
}catch(Exeption $var) {
    process($var);
}catch(MyException $e){
    process($e)
}finally{
    dosomething();
}</code>
Copy after login

使用try catch语句,需要注意:

  • 当我们抛出异常时,会实例化一个异常类,此异常类可以自己定义,但在catch语句中,我们需要规定要捕获的异常对象的类名,并且只能捕获到特定类的异常对象,当然我们可以在最后捕获一个异常基类(PHP内置异常类)来确保异常一定能被捕获。
  • 在抛出异常时,程序会被终止,并回溯代码找到第一个能捕获到它的catch语句,try catch语句是可以嵌套的,并且如上面代码所示 cacth语句是可以多次定义的。
  • finally块会在try catch块结束后执行,即使在try catch块中使用return返回,程序没有执行到最后。

框架里的异常处理

说了那么多异常相关(当然解释这些也是为了能理解和使用框架),那么框架里要怎么实现呢?

重写异常类

我们可以重写异常类,完善其内部方法:

<code class="none"><?php  
class Exception  
{  
    protected $message = 'Unknown exception';   // 异常信息  
    protected $code = 0;                        // 异常代码  
    protected $file;                            // 发生异常的文件名  
    protected $line;                            // 发生异常的代码行号  

    function __construct($message = null, $code = null,$previous_exeception = null);  

    final function getMessage();                // 返回异常信息  
    final function getCode();                   // 返回异常代码  
    final function getFile();                   // 返回发生异常的文件名  
    final function getLine();                   // 返回发生异常的代码行号  
    final function getTrace();                  // 返回异常trace数组  
    final function getTraceAsString();          // 返回异常trace信息

    /**
     * 记录错误日志
     */
    protected function log(){
        Logger::debug();
    }
}  </code>
Copy after login

如上,final方法是不可以重写的,除此之外,我们可以定义自己的方法,如记录异常日志,像我自定义的log方法,在catch代码块中,就可以直接使用$e->log来记录一个异常日志了。

注册全局异常方法

我们可以使用set_exception_handler('exceptionHandler')来全局捕获没有被catch块捕获到的异常,此异常处理函数需要传入一个异常处理对象,这样可以分析此异常处理信息,避免系统出现不人性化的提示,增强框架的健壮性。

<code class="none">function exceptionHandler($e) {
    echo '有未被捕获的异常,在' . $e->getFile() . "的" . $e->getLine() . "行!";
}</code>
Copy after login

其他全局函数

顺便再说一下其他的全局处理函数:

  • set_shutdown_function('shutDownHandler')来执行脚本结束时的函数,此函数即使是在ERROR结束后,也会自动调用。
  • set_error_handler('errorHandler')在PHP发生错误时自动调用,注意,必须在已注册错误函数后才发出的错误才会调用。函数参数形式应为($errno, $errstr, $errfile, $errline);

但是要注意这些全局函数需要在代码段的前面已经定义过再注册。


数据表和Model类的ActiveRecord映射

初次使用yii2的ActivceRecord类觉得好方便,只需要定义其字段同名属性再调用save方法就OK了(好神奇啊),它是怎么实现的呢,看了下源码,明白了其大致实现过程(基类)。


结语

感觉好久没写博客了,‘毕业’对于一个类似专科学习方式的人来说是有些繁琐了,保存好对学校的留恋,继续出发。

真是越学习越觉得自己认识不够,在看一些PHP框架源码时,有时候会感觉自己还差得很远,那种整体感和布局感,估计需要时间和经验的积累吧。

因为框架的应用和自己现在的工作关系不是特别大,而且自己最近在努力学习一些编程底层类的东西,所以框架系列可能会有些‘便秘’,会写点其他的。。。这两天准备换地方住了,跑着看房子了,原谅我‘短’一点。。

哈哈,欢迎继续关注我的博客,嗯,一直在用心。

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles