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

Table of Contents
If you want to install PHP version(s), you can php version
重寫異常類
注冊(cè)全局異常方法
其他全局函數(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)容有:

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

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

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

個(gè)人總結(jié)其優(yōu)點(diǎn)如下:

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

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

PHP內(nèi)置有Exception類,使得我們可以通過實(shí)例化異常類來拋出異常。我們將代碼放在try語句中執(zhí)行,并在其后用catch試圖捕捉到在try代碼塊中拋出的異常,并對(duì)異常進(jìn)行處理。我們還可以在catch代碼段后使用finally語句塊,無論是否有異常都會(huì)執(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)我們拋出異常時(shí),會(huì)實(shí)例化一個(gè)異常類,此異常類可以自己定義,但在catch語句中,我們需要規(guī)定要捕獲的異常對(duì)象的類名,并且只能捕獲到特定類的異常對(duì)象,當(dāng)然我們可以在最后捕獲一個(gè)異常基類(PHP內(nèi)置異常類)來確保異常一定能被捕獲。
  • 在拋出異常時(shí),程序會(huì)被終止,并回溯代碼找到第一個(gè)能捕獲到它的catch語句,try catch語句是可以嵌套的,并且如上面代碼所示 cacth語句是可以多次定義的。
  • finally塊會(huì)在try catch塊結(jié)束后執(zhí)行,即使在try catch塊中使用return返回,程序沒有執(zhí)行到最后。

框架里的異常處理

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

重寫異常類

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

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

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

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

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

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

注冊(cè)全局異常方法

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

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

其他全局函數(shù)

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

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

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


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

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


結(jié)語

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

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

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

哈哈,歡迎繼續(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 do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

How do I validate user input in PHP to ensure it meets certain criteria? How do I validate user input in PHP to ensure it meets certain criteria? Jun 22, 2025 am 01:00 AM

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

What is data serialization in PHP (serialize(), unserialize())? What is data serialization in PHP (serialize(), unserialize())? Jun 22, 2025 am 01:03 AM

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

How do I embed PHP code in an HTML file? How do I embed PHP code in an HTML file? Jun 22, 2025 am 01:00 AM

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

See all articles