扩展Laravel Eloquent\Collection类

扩展Laravel Eloquent\Collection类,laravel,laravel-4,Laravel,Laravel 4,我知道默认的Eloquent\Collection类可以使用以下方法在您的模型中重写: public function newCollection(array $models = array()) { return new CustomCollection($models); } 如果我使用典型的查询,例如: Model::where('name', $name)->get(); 这非常好,因此我可以向Elount collection类添加方法,例如: $records =

我知道默认的
Eloquent\Collection
类可以使用以下方法在您的模型中重写:

public function newCollection(array $models = array()) {

    return new CustomCollection($models);
}
如果我使用典型的查询,例如:

Model::where('name', $name)->get();
这非常好,因此我可以向Elount collection类添加方法,例如:

$records = Model::where('name', $name)->get();

$records->toTable();
但如果我在模型上使用分页,例如:

Model::where('name', $name)->paginate(25);
它返回类
illumb\Support\Collection
的实例,而不是
illumb\Database\elogent\Collection

是否有方法覆盖或扩展典型的
illumb\Support\Collection

我正在尝试向返回的集合添加一个
toTable()
方法。我宁愿不必用我自己的服务提供商来取代分页服务提供商


谢谢

您需要在分页库中的几个其他类中替换分页服务提供程序。听上去,你知道如何用这种方法,但我们希望得到另一个答案,但由于我有代码,我会把它放在这里给你

您需要替换这些类/方法的原因是,Illumb中的文件直接引用Illumb命名空间中类的实例

在config/app.php中

替换

'Illuminate\Pagination\PaginationServiceProvider',

在自动加载程序能够找到的地方创建一个名为ExtendedPaginationServiceProvider.php的新文件,并在其中放置以下内容

<?php

use Illuminate\Support\ServiceProvider;

class ExtendedPaginationServiceProvider extends ServiceProvider
{
    /**
     * @inheritdoc
     */
    public function register()
    {
        $this->app->bindShared('paginator', function($app)
        {
            $paginator = new ExtendedPaginationFactory($app['request'], $app['view'], $app['translator']);

            $paginator->setViewName($app['config']['view.pagination']);

            $app->refresh('request', $paginator, 'setRequest');

            return $paginator;
        });
    }
}
<?php

use Illuminate\Pagination\Factory;

class ExtendedPaginationFactory extends Factory
{
    /**
     * @inheritdoc
     */
    public function make(array $items, $total, $perPage = null)
    {
        $paginator = new ExtendedPaginationPaginator($this, $items, $total, $perPage);

        return $paginator->setupPaginationContext();
    }
}
<?php

use Illuminate\Pagination\Paginator;

class ExtendedPaginationPaginator extends Paginator
{
    /**
     * Get a collection instance containing the items.
     *
     * @return ExtendedCollection
     */
    public function getCollection()
    {
        return new ExtendedCollection($this->items);
    }
}
<?php

use Illuminate\Support\Collection;

class ExtendedCollection extends Collection
{

}

是的,你完全正确,我已经没有选择了,所以我必须更换服务提供商。尽管我很高兴更换服务提供商是一种选择。非常感谢对此的深入回应
<?php

use Illuminate\Support\Collection;

class ExtendedCollection extends Collection
{

}
composer dump-autoload