.
QuestionWhile practicing Redis, I found that if you want to use advanced methods, such as
hSet,
hGet, etc., you must first return the handle, Then it can be executed. As you can see below <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"><?php
namespace 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', '1', 'tom'));// int(1)
}
}</pre><div class="contentsignin">Copy after login</div></div>
, the execution was successful. The question is why the handle should be returned first, which can be solved using the magic method __call
.
Tracking source codeSince you have doubts, you must clear them up. Tracking the source code, I saw
, and found that there was indeed no
__call, just handler
to return the handle to execute advanced methods. . I don’t understand why __clss
is not used. Solving the problem
The solution is to add the
method in
thinkphp/library/think/cache/Driver.php, so that not only Redis can Use the high-level method directly, and other Cache classes that inherit this file can use it directly. The code is as follows<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> /**
* 执行高级方法
* @param $method
* @param $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return call_user_func_array(array($this->handler(), $method), $parameters);
}</pre><div class="contentsignin">Copy after login</div></div>
Look at the test code<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"><?php
namespace 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)
}
}</pre><div class="contentsignin">Copy after login</div></div>
This problem has been solved. When I finished the modification, I remembered that Laravel seemed to use
, and then I looked at the source code, and it was indeed the case. There is the following code in
ravel/vendor/laravel/framework/src/Illuminate/Redis/RedisManager.php<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> /**
* 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);
}</pre><div class="contentsignin">Copy after login</div></div>
ConclusionIn fact, the symbolic meaning of this small modification Greater than practical significance, after all, this is not a bug, it can also be achieved using