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

Table of Contents
搭建自己的PHP框架心得(二),搭建php框架心得
續(xù)言
回調(diào)函數(shù)
VIEW層和ob函數(shù)
類__URL__常量和全局類
用單例模式定義數(shù)據(jù)庫連接基類
DB類的sql查詢函數(shù)
后續(xù)
Home Backend Development PHP Tutorial Experience in building your own PHP framework (2), experience in building PHP framework_PHP tutorial

Experience in building your own PHP framework (2), experience in building PHP framework_PHP tutorial

Jul 12, 2016 am 08:55 AM
php

搭建自己的PHP框架心得(二),搭建php框架心得

續(xù)言

對(duì)于本次更新,我想說:

  • 本框架由本人挑時(shí)間完善,而我還不是PHP大神級(jí)的人物,所以框架漏洞難免,求大神們指出。
  • 本框架的知識(shí)點(diǎn)應(yīng)用都會(huì)寫在博客里,大家有什么異議的可以一起討論,也希望看博客的也能學(xué)習(xí)到它們。
  • 本次更新,更新了函數(shù)規(guī)范上的一些問題,如將函數(shù)盡量的獨(dú)立化,每一個(gè)函數(shù)盡量只單獨(dú)做好一件事情,盡量減少函數(shù)依賴。還對(duì)框架的整體優(yōu)化了一下,添加了SQ全局類,用以處理全局函數(shù),變量。

再次貼出GITHUB地址:Sqier框架GITHUB地址


回調(diào)函數(shù)

替換了很low的類名拼裝實(shí)例化,然后拼裝方法名的用法,使用PHP的回調(diào)函數(shù)方式:

原代碼:

<code>$controller_name = 'Controller\\' . self::$c_name;
$action_name = self::$a_name . 'Action';
$controller = new $controller_name();
$controller->$action_name();
</code>

修改后代碼

<code>    $controller_name = 'Controller\\' . self::$c_name;
    $controller = new $controller_name();
    call_user_func([
        $controller,
        self::$a_name . 'Action'
    ]);
</code>

這里介紹一下PHP的函數(shù)回調(diào)應(yīng)用方式:call_user_func和call_user_func_array:

<p>call_user_func ( callback $function [, mixed $parameter [, mixed $... ]] )</p>
<p>調(diào)用第一個(gè)參數(shù)所提供的用戶自定義的函數(shù)。</p>
<p>返回值:返回調(diào)用函數(shù)的結(jié)果,或FALSE。</p>

call_user_func_array()的用法跟call_user_func類似,只不過傳入的參數(shù)params整體為一個(gè)數(shù)組。

另外,call_user_func系列函數(shù)還可以傳入在第一個(gè)參數(shù)里傳入匿名參數(shù),可以很方便的回調(diào)某些事件,這些特性在復(fù)雜的框架里應(yīng)用也十分廣泛,如yii2的事件機(jī)制里回調(diào)函數(shù)的使用就是基于此。


VIEW層和ob函數(shù)

框架在controller的基類中定義了render方法來渲染頁面,它會(huì)調(diào)用類VIEW的靜態(tài)函數(shù)來分析加載對(duì)應(yīng)頁面的模板。

<code>public static function display($data, $view_file) {

    if(is_array($data)) {
        extract($data);//extract函數(shù)解析$data數(shù)組中的變量
    }else {
        //拋出變量類型異常
    }

    ob_start();
    ob_implicit_flush(0);
    include self::checkTemplate($view_file);//自定義checkTemplate函數(shù),分析檢查對(duì)應(yīng)的函數(shù)模板,正常返回路徑
    $content = ob_get_clean();

    echo $content;
}
</code>

這里重點(diǎn)說一下ob(output buffering)系列函數(shù),其作用引用簡(jiǎn)明代魔法的ob作用介紹:

  • 防止在瀏覽器有輸出之后再使用setcookie,或者h(yuǎn)eader,session_start函數(shù)造成的錯(cuò)誤。其實(shí)這樣的用法少用為好,養(yǎng)成良好的代碼習(xí)慣。
  • 捕捉對(duì)一些不可獲取的函數(shù)的輸出,比如phpinfo會(huì)輸出一大堆的HTML,但是我們無法用一個(gè)變量例如$info=phpinfo();來捕捉,這時(shí)候ob就管用了。
  • 對(duì)輸出的內(nèi)容進(jìn)行處理,例如進(jìn)行g(shù)zip壓縮,例如進(jìn)行簡(jiǎn)繁轉(zhuǎn)換,例如進(jìn)行一些字符串替換。
  • 生成靜態(tài)文件,其實(shí)就是捕捉整頁的輸出,然后存成文件,經(jīng)常在生成HTML,或者整頁緩存中使用。

它在ob_start()函數(shù)執(zhí)行后,打開緩沖區(qū),將后面的輸出內(nèi)容裝進(jìn)系統(tǒng)的緩沖區(qū),ob_implicit_flush(0)函數(shù)來關(guān)閉絕對(duì)刷送(echo等),最后使用ob_get_clean()函數(shù)將緩沖區(qū)的內(nèi)容取出來。


類__URL__常量和全局類

TP里的__URL__等全局常量用著很方便,可以很簡(jiǎn)單的實(shí)現(xiàn)跳轉(zhuǎn)等操作,而定義它的函數(shù)createUrl函數(shù)我又想重用,于是借鑒YII的全局類定義方法:

定義基類及詳細(xì)方法(以后的全局方法會(huì)寫在這里)

<code>class BaseSqier{
    //方法根據(jù)傳入的$info信息,和當(dāng)前URL_MODE解析返回URL字符串
    public static function createUrl($info = '') {
        $url_info = explode('/', strtolower($info));
        $controller = isset($url_info[1]) ? $url_info[0] : strtolower(CONTROLLER);
        $action = isset($url_info[1]) ? $url_info[1] : $url_info[0];
        switch(URL_MODE){
            case URL_COMMON:
                return "/index.php?r=" . $controller . '/' . $action;
            case URL_REWRITE:
                return '/' .$controller . '/' . $action;
        }
    }
 }
</code>

在啟動(dòng)文件中定義類并繼承基類;

<code>require_once SQ_PATH.'BaseSqier.php';
class SQ extends BaseSqier{
}
</code>

在全局內(nèi)都可以直接使用SQ::createUrl()方法來創(chuàng)建URL了。這樣,定義__URL__常量就很輕松了。


用單例模式定義數(shù)據(jù)庫連接基類

<code>class Db {
    protected static $_instance;
    public static function getInstance() {
        if(!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    private function __construct() {
        $link = new \mysqli(DB_HOST, DB_USER, DB_PWD, DB_NAME) or die("連接數(shù)據(jù)庫失敗,請(qǐng)檢查數(shù)據(jù)庫配置信息!");
        $link->query('set names utf8');
    }
    public function __clone() {
        return self::getInstance();
    }
}
</code>

使用單例模式的核心是:

  • 私有化構(gòu)造函數(shù),使無法用new來創(chuàng)建對(duì)象,也防止子類繼承它并改寫其構(gòu)造函數(shù);
  • 用靜態(tài)變量存放當(dāng)前對(duì)象,定義靜態(tài)方法來返回對(duì)象,如對(duì)象還未實(shí)例化,實(shí)例化一個(gè),存入靜態(tài)變量并返回。
  • 構(gòu)造其__clone魔術(shù)方法,防止clone出一個(gè)新的對(duì)象;

DB類的sql查詢函數(shù)

DB查詢函數(shù)是一個(gè)很復(fù)雜的部分,它是一個(gè)自成體系的東西,像TP和YII的查詢方法都有其獨(dú)特的地方。我這里暫時(shí)先借用TP的MODEL基類,有時(shí)間再慢慢補(bǔ)這個(gè)。

嗯,介紹一下像TP的查詢里的方法聯(lián)查的實(shí)現(xiàn),其訣竅在于,在每個(gè)聯(lián)查方法的最后都用 return this 來返回已處理過的查詢對(duì)象。


后續(xù)

yii2里的數(shù)據(jù)表和model類屬性之間的映射很酷(雖然被深坑過), 前面一直避開的模塊(module,我可以想像得到把它也添加到URI時(shí)解析的麻煩)有時(shí)間考慮一下。

邊寫邊優(yōu)化。

Well, to be continued... By the way, promote your personal website: www.alwayscoding.cn My contact information is on the right side of the message board page. If you have any questions, you can communicate there.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1116381.htmlTechArticleExperiences in building your own PHP framework (2), Continuation of experience in building PHP frameworks For this update, I want to say : This framework is perfected by myself, and I am not a PHP master yet, so...
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 get the current session ID in PHP? How to get the current session ID in PHP? Jul 13, 2025 am 03:02 AM

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

PHP get substring from a string PHP get substring from a string Jul 13, 2025 am 02:59 AM

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

How do you perform unit testing for php code? How do you perform unit testing for php code? Jul 13, 2025 am 02:54 AM

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

How to split a string into an array in PHP How to split a string into an array in PHP Jul 13, 2025 am 02:59 AM

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

How to pass a session variable to another page in PHP? How to pass a session variable to another page in PHP? Jul 13, 2025 am 02:39 AM

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

How does PHP handle Environment Variables? How does PHP handle Environment Variables? Jul 14, 2025 am 03:01 AM

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

See all articles