簡介
- 本章的初衷是由於在閱讀源碼的過程當中對身心形成了巨大的傷害而做。 😝
【coquettish one】 - 無處不在的 [...]
// 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對象
}
複製代碼
【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
還能夠
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會自動忽略多餘的參數。
若是閉包再多聲明一個參數? (直接💥)
複製代碼