使用场景:
Laravel为Eloquent的集合提供了开箱即用的分页,但不能在普通集合上使用它。集合有forPage()方法,但它的级别更低,因此它不生成分页链接。因此,您必须创建一个LengthAwarePaginator实例。但是,如果您希望与Eloquent的集合相同呢?然后使用macro!
这样做的好处是,语法和输出几乎与Eloquent集合paginate()方法相同,因此在测试时可以(相对地)轻松地将其替换为Eloquent集合。
有两种方法:
1. 使用
macro
可以将集合
macro
添加到服务提供程序。这样就可以对任何集合调用paginate()
collect([ ... ])->paginate( 20 );
2. The subclass way
Where you want a “pageable” collection that is distinct from the standard
Illuminate\Support\Collection
, implement a copy of
Collection.php
in your application and simply replace your
use Illuminate\Support\Collection
statements at the top of your dependent files with
use App\Support\Collection
:
// use Illuminate\Support\Collection
use App\Support\Collection;
$items = [];
$collection = (new Collection($items))->paginate(20);
注意,此方法不能与collect()助手函数一起使用
<?php
namespace App\Providers;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
/**
* Paginate a standard Laravel Collection.
*
* @param int $perPage
* @param int $total
* @param int $page
* @param string $pageName
* @return array
*/
Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage)->values(),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
}
}
<?php
namespace App\Support;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection as BaseCollection;
class Collection extends BaseCollection
{
public function paginate($perPage, $total = null, $page = null, $pageName = 'page')
{
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage)->values(),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
}
}