


Experience in building your own PHP framework (2), experience in building PHP framework_PHP tutorial
Jul 12, 2016 am 08:55 AM搭建自己的PHP框架心得(二),搭建php框架心得
續(xù)言
對于本次更新,我想說:
- 本框架由本人挑時間完善,而我還不是PHP大神級的人物,所以框架漏洞難免,求大神們指出。
- 本框架的知識點應(yīng)用都會寫在博客里,大家有什么異議的可以一起討論,也希望看博客的也能學(xué)習(xí)到它們。
- 本次更新,更新了函數(shù)規(guī)范上的一些問題,如將函數(shù)盡量的獨立化,每一個函數(shù)盡量只單獨做好一件事情,盡量減少函數(shù)依賴。還對框架的整體優(yōu)化了一下,添加了SQ全局類,用以處理全局函數(shù),變量。
再次貼出GITHUB地址:Sqier框架GITHUB地址
回調(diào)函數(shù)
替換了很low的類名拼裝實例化,然后拼裝方法名的用法,使用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)用第一個參數(shù)所提供的用戶自定義的函數(shù)。</p> <p>返回值:返回調(diào)用函數(shù)的結(jié)果,或FALSE。</p>
call_user_func_array()的用法跟call_user_func類似,只不過傳入的參數(shù)params整體為一個數(shù)組。
另外,call_user_func系列函數(shù)還可以傳入在第一個參數(shù)里傳入匿名參數(shù),可以很方便的回調(diào)某些事件,這些特性在復(fù)雜的框架里應(yīng)用也十分廣泛,如yii2的事件機制里回調(diào)函數(shù)的使用就是基于此。
VIEW層和ob函數(shù)
框架在controller的基類中定義了render方法來渲染頁面,它會調(diào)用類VIEW的靜態(tài)函數(shù)來分析加載對應(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ù),分析檢查對應(yīng)的函數(shù)模板,正常返回路徑 $content = ob_get_clean(); echo $content; } </code>
這里重點說一下ob(output buffering)系列函數(shù),其作用引用簡明代魔法的ob作用介紹:
- 防止在瀏覽器有輸出之后再使用setcookie,或者header,session_start函數(shù)造成的錯誤。其實這樣的用法少用為好,養(yǎng)成良好的代碼習(xí)慣。
- 捕捉對一些不可獲取的函數(shù)的輸出,比如phpinfo會輸出一大堆的HTML,但是我們無法用一個變量例如$info=phpinfo();來捕捉,這時候ob就管用了。
- 對輸出的內(nèi)容進行處理,例如進行g(shù)zip壓縮,例如進行簡繁轉(zhuǎn)換,例如進行一些字符串替換。
- 生成靜態(tài)文件,其實就是捕捉整頁的輸出,然后存成文件,經(jīng)常在生成HTML,或者整頁緩存中使用。
它在ob_start()函數(shù)執(zhí)行后,打開緩沖區(qū),將后面的輸出內(nèi)容裝進系統(tǒng)的緩沖區(qū),ob_implicit_flush(0)函數(shù)來關(guān)閉絕對刷送(echo等),最后使用ob_get_clean()函數(shù)將緩沖區(qū)的內(nèi)容取出來。
類__URL__常量和全局類
TP里的__URL__等全局常量用著很方便,可以很簡單的實現(xiàn)跳轉(zhuǎn)等操作,而定義它的函數(shù)createUrl函數(shù)我又想重用,于是借鑒YII的全局類定義方法:
定義基類及詳細方法(以后的全局方法會寫在這里)
<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>
在啟動文件中定義類并繼承基類;
<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ù)庫失敗,請檢查數(shù)據(jù)庫配置信息!"); $link->query('set names utf8'); } public function __clone() { return self::getInstance(); } } </code>
使用單例模式的核心是:
- 私有化構(gòu)造函數(shù),使無法用new來創(chuàng)建對象,也防止子類繼承它并改寫其構(gòu)造函數(shù);
- 用靜態(tài)變量存放當(dāng)前對象,定義靜態(tài)方法來返回對象,如對象還未實例化,實例化一個,存入靜態(tài)變量并返回。
- 構(gòu)造其__clone魔術(shù)方法,防止clone出一個新的對象;
DB類的sql查詢函數(shù)
DB查詢函數(shù)是一個很復(fù)雜的部分,它是一個自成體系的東西,像TP和YII的查詢方法都有其獨特的地方。我這里暫時先借用TP的MODEL基類,有時間再慢慢補這個。
嗯,介紹一下像TP的查詢里的方法聯(lián)查的實現(xiàn),其訣竅在于,在每個聯(lián)查方法的最后都用 return this
來返回已處理過的查詢對象。
后續(xù)
yii2里的數(shù)據(jù)表和model類屬性之間的映射很酷(雖然被深坑過), 前面一直避開的模塊(module,我可以想像得到把它也添加到URI時解析的麻煩)有時間考慮一下。
邊寫邊優(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.

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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

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

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.

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.

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