Collection.php
/**
* @property-read HigherOrderCollectionProxy $average
* @property-read HigherOrderCollectionProxy $avg
* @property-read HigherOrderCollectionProxy $contains
* @property-read HigherOrderCollectionProxy $each
* @property-read HigherOrderCollectionProxy $every
* @property-read HigherOrderCollectionProxy $filter
* @property-read HigherOrderCollectionProxy $first
* @property-read HigherOrderCollectionProxy $flatMap
* @property-read HigherOrderCollectionProxy $groupBy
* @property-read HigherOrderCollectionProxy $keyBy
* @property-read HigherOrderCollectionProxy $map
* @property-read HigherOrderCollectionProxy $max
* @property-read HigherOrderCollectionProxy $min
* @property-read HigherOrderCollectionProxy $partition
* @property-read HigherOrderCollectionProxy $reject
* @property-read HigherOrderCollectionProxy $sortBy
* @property-read HigherOrderCollectionProxy $sortByDesc
* @property-read HigherOrderCollectionProxy $sum
* @property-read HigherOrderCollectionProxy $unique
*
* Class Collection
*/
/**
* The methods that can be proxied.
*
* @var array
*/
protected static $proxies = [
'average', 'avg', 'contains', 'each', 'every', 'filter', 'first',
'flatMap', 'groupBy', 'keyBy', 'map', 'max', 'min', 'partition',
'reject', 'sortBy', 'sortByDesc', 'sum', 'unique',
];
/**
* Dynamically access collection proxies.
*
* @param string $key
* @return mixed
*
* @throws \Exception
*/
public function __get($key)
{
if (! in_array($key, static::$proxies)) {
throw new Exception("Property [{$key}] does not exist on this collection instance.");
}
return new HigherOrderCollectionProxy($this, $key);
}
HigherOrderCollectionProxy.php
/**
* Create a new proxy instance.
*
* @param \Illuminate\Support\Collection $collection
* @param string $method
* @return void
*/
public function __construct(Collection $collection, $method)
{
$this->method = $method;
$this->collection = $collection;
}
/**
* Proxy accessing an attribute onto the collection items.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
return $this->collection->{$this->method}(function ($value) use ($key) {
return is_array($value) ? $value[$key] : $value->{$key};
});
}
/**
* Proxy a method call onto the collection items.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return $this->collection->{$this->method}(function ($value) use ($method, $parameters) {
return $value->{$method}(...$parameters);
});
}
我的问题是这里为什么要用 HigherOrderCollectionProxy 来代理,有什么好处?这些方法都是 public 形式的,直接调用方法不好吗?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.