Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom query operators support #161

Merged
merged 4 commits into from Apr 29, 2016
Merged

Custom query operators support #161

merged 4 commits into from Apr 29, 2016

Conversation

marcojetson
Copy link
Contributor

@marcojetson marcojetson commented Apr 28, 2016

Provides a way to add custom query operators.
Supports either a callback or a class string implementing callable.

public static void \Spot\Query::addWhereOperator ( string $operator, callable|string $action )

Adds a new operator to the query's where parser.

Parameters

operator

Operator token

action

Operator handler. Either a callable or a class name implementing __invoke.

Errors/Exceptions

Emits Spot\Exception if the operator already exists.

Examples

<?php

// using a callback
\Spot\Query::addWhereOperator(':json_exists', function ($builder, $column, $value) {
    return 'jsonb_exists(' . $column . ', ' . $builder->createPositionalParameter($value) . ')';
});

// using a class
class JsonEquals
{
    public function __invoke(Doctrine\DBAL\Query\QueryBuilder $builder, $column, $value)
    {
        return $column . '::text = ' . $builder->createPositionalParameter($value);
    }
}

\Spot\Query::addWhereOperator(':json_equals', JsonEquals::class);

Making Query::parseWhereToSQLFragments protected allows someone to override it and add custom operators (such as JSONB operators)
@nebulousGirl
Copy link
Contributor

Just curious. Why are you passing a class string instead of a new instance of the class in the __invoke example?

@marcojetson
Copy link
Contributor Author

marcojetson commented Apr 29, 2016

It will also work if you pass a new instance, but I wanted to add a class reference to the example.
Reasons to allow a class references are:

  • Being able to specify defaults in Spot\Query::$_operators
  • Lazy instantiation, makes no sense to create every operator instance on every request

In addition \Spot\Query is using flyweight pattern and sharing operator instances across Query instances.

@vlucas
Copy link
Collaborator

vlucas commented Apr 29, 2016

Looks good. Thanks for the effort on this @marcojetson.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants