Laravel源码中为何有大量依赖于class的trait
最近在阅读 laravel 源码,发现有不少 trait 引用了下级 class 的方法和属性,我觉得这种设计是有问题的,trait 如果依赖于 class 的方法,如何保证其复用性,例如:8.* 版本中的 Illuminate\Http\Concerns\InteractsWithInput:
namespace Illuminate\Http\Concerns;
trait InteractsWithInput
{
public function input($key = null, $default = null)
{
return data_get(
//getInputSource方法在当前trait中不存在
$this->getInputSource()->all() + $this->query->all(), $key, $default);
}
}
namespace Illuminate\Http;
class Request extends SymfonyRequest implements Arrayable, ArrayAccess
{
use Concerns\InteractsWithContentTypes,
Concerns\InteractsWithFlashData,
Concerns\InteractsWithInput,
Macroable;
//getInputSource定义在这里
protected function getInputSource()
{
if ($this->isJson()) {
return $this->json();
}
return in_array($this->getRealMethod(), ['GET', 'HEAD']) ? $this->query : $this->request;
}
}
这样的问题在源码里能看到几处,很不理解,不知道这么设计是什么原因
推荐文章: