亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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)容有:

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

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

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

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

  • 可以快速終止流程,重置系統(tǒng)狀態(tài),清理變量和內(nèi)存占用,在普通WEB應(yī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代碼塊中拋出的異常,并對異常進(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ī)定要捕獲的異常對象的類名,并且只能捕獲到特定類的異常對象,當(dāng)然我們可以在最后捕獲一個(gè)異?;悾≒HP內(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ā)生異常的代碼行號  

    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信息

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

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

注冊全局異常方法

我們可以使用set_exception_handler('exceptionHandler')來全局捕獲沒有被catch塊捕獲到的異常,此異常處理函數(shù)需要傳入一個(gè)異常處理對象,這樣可以分析此異常處理信息,避免系統(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)用,注意,必須在已注冊錯(cuò)誤函數(shù)后才發(fā)出的錯(cuò)誤才會(huì)調(diào)用。函數(shù)參數(shù)形式應(yīng)為($errno, $errstr, $errfile, $errline);

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


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

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


結(jié)語

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

真是越學(xué)習(xí)越覺得自己認(rèn)識不夠,在看一些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 to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

PHP integrated AI intelligent picture recognition PHP visual content automatic labeling PHP integrated AI intelligent picture recognition PHP visual content automatic labeling Jul 25, 2025 pm 05:42 PM

The core idea of integrating AI visual understanding capabilities into PHP applications is to use the third-party AI visual service API, which is responsible for uploading images, sending requests, receiving and parsing JSON results, and storing tags into the database; 2. Automatic image tagging can significantly improve efficiency, enhance content searchability, optimize management and recommendation, and change visual content from "dead data" to "live data"; 3. Selecting AI services requires comprehensive judgments based on functional matching, accuracy, cost, ease of use, regional delay and data compliance, and it is recommended to start from general services such as Google CloudVision; 4. Common challenges include network timeout, key security, error processing, image format limitation, cost control, asynchronous processing requirements and AI recognition accuracy issues.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

How to use PHP to develop AI-driven advertising delivery PHP advertising performance optimization solution How to use PHP to develop AI-driven advertising delivery PHP advertising performance optimization solution Jul 25, 2025 pm 06:12 PM

PHP provides an input basis for AI models by collecting user data (such as browsing history, geographical location) and pre-processing; 2. Use curl or gRPC to connect with AI models to obtain click-through rate and conversion rate prediction results; 3. Dynamically adjust advertising display frequency, target population and other strategies based on predictions; 4. Test different advertising variants through A/B and record data, and combine statistical analysis to optimize the effect; 5. Use PHP to monitor traffic sources and user behaviors and integrate with third-party APIs such as GoogleAds to achieve automated delivery and continuous feedback optimization, ultimately improving CTR and CVR and reducing CPC, and fully implementing the closed loop of AI-driven advertising system.

See all articles