本篇文章給大家?guī)?lái)的內(nèi)容是關(guān)于ThinkPHP 5.1修改Cache 源碼的方法介紹(代碼示例),有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)你有所幫助。
最近在學(xué)習(xí) THinkPHP 5.1,看了 Cache 方法的操作,有一點(diǎn)疑惑。雖然封裝了很多方法,使用的時(shí)候很方便,但是對(duì) Redis 的高級(jí)操作好像不是很友好,出于學(xué)習(xí)的目的,對(duì)源碼進(jìn)行了一點(diǎn)小修改。首先聲明兩點(diǎn):一是此次的修改,只是個(gè)人觀點(diǎn),不適于所有人;二是此次修改僅為學(xué)習(xí)所用,各位謹(jǐn)慎修改源碼。
問題
在練習(xí) Redis 的時(shí)候,發(fā)現(xiàn)如果想要使用高級(jí)方法,例如 hSet、hGet 等,要先返回句柄,然后才能執(zhí)行。如下
?phpnamespace app/index/controller;use think/cache/driver/Redis;use think/Controller;html' target='_blank'>class RedisTest extends Controller public function index() $redis = new Redis(); $redis = $redis- handler(); dump($redis- hSet( h_name , 1 , tom // int(1)}
可以看到,執(zhí)行成功。問題是為什么要先返回句柄,可以用 __call 這種魔術(shù)方法來(lái)解決的。
追蹤源碼
既然有了疑惑,就要解惑。追蹤著源碼,看到 thinkphp/library/think/cache/Driver.php,發(fā)現(xiàn)確實(shí)沒有 __call,只是 handler 來(lái)返回句柄來(lái)執(zhí)行高級(jí)方法。沒想明白為什么不用 __clss。
解決問題
解決方法就是在 thinkphp/library/think/cache/Driver.php 中添加 __call 方法,這樣不止 Redis 可以直接使用高級(jí)方法,其他繼承此文件的 Cache 類都可以直接使用。代碼如下
/** * 執(zhí)行高級(jí)方法 * @param $method * @param $parameters * @return mixed public function __call($method, $parameters) return call_user_func_array(array($this- handler(), $method), $parameters); }
再看下測(cè)試代碼
?phpnamespace app/index/controller;use think/cache/driver/Redis;use think/Controller;class RedisTest extends Controller public function index() $redis = new Redis();// $redis = $redis- handler(); dump($redis- hSet( h_name , 2 , jerry // int(1)}
到此問題已解決。當(dāng)我修改完的時(shí)候,想起 Laravel 似乎就是用的 __call,然后去看了源碼,確實(shí)如此。在 ravel/vendor/laravel/framework/src/Illuminate/Redis/RedisManager.php 中有如下代碼
/** * Pass methods onto the default Redis connection. * @param string $method * @param array $parameters * @return mixed public function __call($method, $parameters) return $this- connection()- {$method}(...$parameters); }
結(jié)語(yǔ)
其實(shí)這次小修改的象征意義大于實(shí)際意義,畢竟這不是什么 bug,使用 handler 也是可以實(shí)現(xiàn)的。對(duì)我來(lái)說(shuō)更大的意義是,遇到些問題會(huì)更傾向于查看源碼。看得多了,自然能力會(huì)提升。
以上就是ThinkPHP 5.1修改Cache 源碼的方法介紹(代碼示例)的詳細(xì)內(nèi)容,PHP教程
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。
新聞熱點(diǎn)
疑難解答
圖片精選