【Laravel-海贼王系列】第十七章,Laravel 那些骚操作

栏目: PHP · 发布时间: 6年前

// Pipeline 的调用逻辑
$response = method_exists($pipe, $this->method)
            ? $pipe->{$this->method}(...$parameters)
            : $pipe(...$parameters);

// Events 的封装
return function ($event, $payload) use ($listener, $wildcard) {
            if ($wildcard) {
                return $listener($event, $payload);
            }
            return $listener(...array_values($payload));
        };

... 的用法可以理解成解构后面的数组按照顺序传递给调用的方法。

// 皮一下:如果数组的 key 不是数字会如何?
   抛出异常:Cannot unpack array with string keys
复制代码

【coquettish two】 - 事件的骚操作

真香用法:app('events')->listen('sao',[$obj,'fuck']);

// 事件对应的封装源码

return function ($event, $payload) use ($listener = [$obj,'fuck'], $wildcard) {
        if ($wildcard) {
            return $listener($event, $payload);
        }
          
        // 此处是最终调用  
        return $listener(...array_values($payload));
    };

// 最终调用变成

[$obj,'fuck'](...array_values($payload));

// 等价代码

call_user_func_array([$obj,'fuck'],...array_values($payload));

复制代码

【coquettish three】 - ArrayAccess 对象用数组访问

普通的代码:  app('events'); // 从容器中获取事件对象

骚操作: app()['events']; // 调用容器的offsetGet方法

public function offsetGet($key)
{
    return $this->make($key); // make一个events对象
}
复制代码
  • 容器实现了 ArrayAccess 接口,按照数组方式访问对象的时候会触发 PHP 指定的方法。详细:ArrayAccess

【coquettish four】 - 容器 bind-make 一些不为人知的秘密

一个常规的用法分析

app()->bind('myclass',function(){reutrn 'test';});
dump(app('myclass')); // 输出 'test';

还可以
app()->bind('myclass',function($app){return $app;});
dump(app('myclass')); // 输出 Application#2 对象

还可以
app()->bind('myclass',function($app,$param){return $param;});
dump(app()->makeWith('myclass',['hhh'=>'vvv']); // 输出 ['hhh'=>'vvv'] 

直接看容器如何 make 一个绑定闭包的返回:
if ($concrete instanceof Closure) {
            return $concrete($this, $this->getLastParameterOverride());
        }

可以看到容器直接执行闭包并返回。

实际执行:
第一个:(function($this, $this->getLastParameterOverride()){return 'test';})();
第二个:(fucntion($this, $this->getLastParameterOverride()){return $this;})();
第三个:(fucntion($this, $this->getLastParameterOverride()){return $this->getLastParameterOverride();})();
...

思考:三个闭包分别声明了【零个,一个,两个】参数但是容器中执行的时候总是传入两个参数,PHP会自动忽略多余的参数。

如果闭包再多声明一个参数? (直接:boom:)
复制代码

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Search User Interfaces

Search User Interfaces

Marti A. Hearst / Cambridge University Press / 2009-9-21 / USD 59.00

搜索引擎的本质是帮助用户更快、更方便、更有效地查找与获取所需信息。在不断改进搜索算法和提升性能(以技术为中心)的同时,关注用户的信息需求、搜寻行为、界面设计与交互模式是以用户为中心的一条并行发展思路。创新的搜索界面及其配套的交互机制对一项搜索服务的成功来说是至关重要的。Marti Hearst教授带来的这本新作《Search User Interfaces》即是后一条思路的研究成果,将信息检索与人......一起来看看 《Search User Interfaces》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具