国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
If you want to install PHP version(s), you can php version
重寫異常類
注冊全局異常方法
其他全局函數(shù)
Home Backend Development PHP Tutorial Build your own PHP framework (3), build PHP framework_PHP tutorial

Build your own PHP framework (3), build PHP framework_PHP tutorial

Jul 12, 2016 am 08:49 AM
php three main build frame my own

If you want to install PHP version(s), you can php version

續(xù)言

接著完善自己的PHP框架,本次更新的主要內(nèi)容有:

  • 介紹了異常處理機制
  • 完善了異常和錯誤處理
  • 數(shù)據(jù)表跟Model類的映射

異常處理
<p>異常處理:異常處理是編程語言或計算機硬件里的一種機制,用于處理軟件或信息系統(tǒng)中出現(xiàn)的異常狀況(即超出程序正常執(zhí)行流程的某些特殊條件)</p>

異常處理用于處理程序中的異常狀況,雖說是“異常狀態(tài)”,但仍然還是在程序編寫人員的預(yù)料之中,其實程序的異常處理完全可以用‘if else’語句來代替,但異常處理自然有其優(yōu)勢之處。

個人總結(jié)其優(yōu)點如下:

  • 可以快速終止流程,重置系統(tǒng)狀態(tài),清理變量和內(nèi)存占用,在普通WEB應(yīng)用中,一次請求結(jié)束后,F(xiàn)AST CGI會自動清理變量和上下文,但如果在PHP的命令行模式執(zhí)行守護腳本時,它的效果就會很方便了。
  • 大量的if else語句會使代碼變得繁雜難懂,使用異常處理可以使程序邏輯更清晰易懂,畢竟處理異常的入口只有catch語句一處。
  • 一量程序中的函數(shù)出現(xiàn)異常結(jié)果或狀況,如果使用函數(shù)的return方式返回異常信息,層層向上,每一次都要進行return判斷。使用異常處理我們可以假設(shè)所有的返回信息都是正常的,避免了大量的代碼重復(fù)。

雖然將代碼放在try catch塊中會有微微的效率差,但是跟這些優(yōu)點一比,這點消耗就不算什么了。那么PHP的異常處理怎么使用呢?

PHP內(nèi)置有Exception類,使得我們可以通過實例化異常類來拋出異常。我們將代碼放在try語句中執(zhí)行,并在其后用catch試圖捕捉到在try代碼塊中拋出的異常,并對異常進行處理。我們還可以在catch代碼段后使用finally語句塊,無論是否有異常都會執(zhí)行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>

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

  • 當(dāng)我們拋出異常時,會實例化一個異常類,此異常類可以自己定義,但在catch語句中,我們需要規(guī)定要捕獲的異常對象的類名,并且只能捕獲到特定類的異常對象,當(dāng)然我們可以在最后捕獲一個異?;悾≒HP內(nèi)置異常類)來確保異常一定能被捕獲。
  • 在拋出異常時,程序會被終止,并回溯代碼找到第一個能捕獲到它的catch語句,try catch語句是可以嵌套的,并且如上面代碼所示 cacth語句是可以多次定義的。
  • finally塊會在try catch塊結(jié)束后執(zhí)行,即使在try catch塊中使用return返回,程序沒有執(zhí)行到最后。

框架里的異常處理

說了那么多異常相關(guān)(當(dāng)然解釋這些也是為了能理解和使用框架),那么框架里要怎么實現(xiàn)呢?

重寫異常類

我們可以重寫異常類,完善其內(nèi)部方法:

<code class="none"><?php  
class Exception  
{  
    protected $message = 'Unknown exception';   // 異常信息  
    protected $code = 0;                        // 異常代碼  
    protected $file;                            // 發(fā)生異常的文件名  
    protected $line;                            // 發(fā)生異常的代碼行號  

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

    final function getMessage();                // 返回異常信息  
    final function getCode();                   // 返回異常代碼  
    final function getFile();                   // 返回發(fā)生異常的文件名  
    final function getLine();                   // 返回發(fā)生異常的代碼行號  
    final function getTrace();                  // 返回異常trace數(shù)組  
    final function getTraceAsString();          // 返回異常trace信息

    /**
     * 記錄錯誤日志
     */
    protected function log(){
        Logger::debug();
    }
}  </code>

如上,final方法是不可以重寫的,除此之外,我們可以定義自己的方法,如記錄異常日志,像我自定義的log方法,在catch代碼塊中,就可以直接使用$e->log來記錄一個異常日志了。

注冊全局異常方法

我們可以使用set_exception_handler('exceptionHandler')來全局捕獲沒有被catch塊捕獲到的異常,此異常處理函數(shù)需要傳入一個異常處理對象,這樣可以分析此異常處理信息,避免系統(tǒng)出現(xiàn)不人性化的提示,增強框架的健壯性。

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

其他全局函數(shù)

順便再說一下其他的全局處理函數(shù):

  • set_shutdown_function('shutDownHandler')來執(zhí)行腳本結(jié)束時的函數(shù),此函數(shù)即使是在ERROR結(jié)束后,也會自動調(diào)用。
  • set_error_handler('errorHandler')在PHP發(fā)生錯誤時自動調(diào)用,注意,必須在已注冊錯誤函數(shù)后才發(fā)出的錯誤才會調(diào)用。函數(shù)參數(shù)形式應(yīng)為($errno, $errstr, $errfile, $errline);

但是要注意這些全局函數(shù)需要在代碼段的前面已經(jīng)定義過再注冊。


數(shù)據(jù)表和Model類的ActiveRecord映射

初次使用yii2的ActivceRecord類覺得好方便,只需要定義其字段同名屬性再調(diào)用save方法就OK了(好神奇?。?,它是怎么實現(xiàn)的呢,看了下源碼,明白了其大致實現(xiàn)過程(基類)。


結(jié)語

感覺好久沒寫博客了,‘畢業(yè)’對于一個類似??茖W(xué)習(xí)方式的人來說是有些繁瑣了,保存好對學(xué)校的留戀,繼續(xù)出發(fā)。

真是越學(xué)習(xí)越覺得自己認識不夠,在看一些PHP框架源碼時,有時候會感覺自己還差得很遠,那種整體感和布局感,估計需要時間和經(jīng)驗的積累吧。

因為框架的應(yīng)用和自己現(xiàn)在的工作關(guān)系不是特別大,而且自己最近在努力學(xué)習(xí)一些編程底層類的東西,所以框架系列可能會有些‘便秘’,會寫點其他的。。。這兩天準備換地方住了,跑著看房子了,原諒我‘短’一點。。

哈哈,歡迎繼續(xù)關(guān)注我的博客,嗯,一直在用心。

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1137574.htmlTechArticleBuild your own PHP framework (3), build the php framework, continue to improve your own PHP framework, this update The main contents are: Introducing the exception handling mechanism and improving exception and error handling...
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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How to combine two php arrays unique values? How to combine two php arrays unique values? Jul 02, 2025 pm 05:18 PM

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

How to use php exit function? How to use php exit function? Jul 03, 2025 am 02:15 AM

exit() is a function in PHP that is used to terminate script execution immediately. Common uses include: 1. Terminate the script in advance when an exception is detected, such as the file does not exist or verification fails; 2. Output intermediate results during debugging and stop execution; 3. Call exit() after redirecting in conjunction with header() to prevent subsequent code execution; In addition, exit() can accept string parameters as output content or integers as status code, and its alias is die().

Applying Semantic Structure with article, section, and aside in HTML Applying Semantic Structure with article, section, and aside in HTML Jul 05, 2025 am 02:03 AM

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

The requested operation requires elevation Windows The requested operation requires elevation Windows Jul 04, 2025 am 02:58 AM

When you encounter the prompt "This operation requires escalation of permissions", it means that you need administrator permissions to continue. Solutions include: 1. Right-click the "Run as Administrator" program or set the shortcut to always run as an administrator; 2. Check whether the current account is an administrator account, if not, switch or request administrator assistance; 3. Use administrator permissions to open a command prompt or PowerShell to execute relevant commands; 4. Bypass the restrictions by obtaining file ownership or modifying the registry when necessary, but such operations need to be cautious and fully understand the risks. Confirm permission identity and try the above methods usually solve the problem.

How to create an array in php? How to create an array in php? Jul 02, 2025 pm 05:01 PM

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color

php raw post data php php raw post data php Jul 02, 2025 pm 04:51 PM

The way to process raw POST data in PHP is to use $rawData=file_get_contents('php://input'), which is suitable for receiving JSON, XML, or other custom format data. 1.php://input is a read-only stream, which is only valid in POST requests; 2. Common problems include server configuration or middleware reading input streams, which makes it impossible to obtain data; 3. Application scenarios include receiving front-end fetch requests, third-party service callbacks, and building RESTfulAPIs; 4. The difference from $_POST is that $_POST automatically parses standard form data, while the original data is suitable for non-standard formats and allows manual parsing; 5. Ordinary HTM

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

How Do You Pass Variables by Value vs. by Reference in PHP? How Do You Pass Variables by Value vs. by Reference in PHP? Jul 08, 2025 am 02:42 AM

InPHP,variablesarepassedbyvaluebydefault,meaningfunctionsorassignmentsreceiveacopyofthedata,whilepassingbyreferenceallowsmodificationstoaffecttheoriginalvariable.1.Whenpassingbyvalue,changestothecopydonotimpacttheoriginal,asshownwhenassigning$b=$aorp

See all articles