spotorm / spot2

Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer
http://phpdatamapper.com
BSD 3-Clause "New" or "Revised" License
601 stars 101 forks source link

Parameters to scopes #167

Closed ThomasCedrini closed 8 years ago

ThomasCedrini commented 8 years ago

Hi !

I want to define a scopes in my mapper but I need to pass some arguments. How can I do that?

Thanks !

PS : Your project is awesome !!

nebulousGirl commented 8 years ago

That is not possible. Scopes are shortcuts to frequently used simple queries.

You should probably add a new method to your mapper instead.

vlucas commented 8 years ago

Actually, it should work. The only thing to note is that the $query object will always be the first parameter: https://github.com/vlucas/spot2/blob/master/lib/Query.php#L793

vlucas commented 8 years ago

You can just define extra parameters on your scope as normal, after the required $query argument:

<?php
namespace SpotTest\Mapper;
use Spot\Mapper;
use Spot\Query;
class Event extends Mapper
{
    /**
     * Custom scopes applied to Spot\Query
     *
     * @return array
     */
    public function scopes()
    {
        return [
            'page' => function (Query $query, $page = 1, $items = 20) {
                return $query->limit($items)->offset($page > 0 ? $page * $items : 0);
            }
        ];
    }
}

And use it like this:

$mapper->where(['type' => 'post'])->page(1);