ValuQuery is a library that provides CSS selector based query language support. ValuQuery can be used with various databases, including NoSQL and relative databases. Currently, MongoDB is best supported and there is also support for Doctrine's object-document mapper for MongoDB.
The core components of ValuQuery are SelectorParser
and QueryBuilder
. SelectorParser
parses a Selector
object from selector string. QueryBuilder
iterates components of Selector
object and passes each component to its listeners, which in turn parse the query properties.
There are pre-built listeners for MongoDB and a separate listener for Doctrine's MongoODM.
Initializing query builder:
$queryBuilder = new ValuQuery\QueryBuilder\QueryBuilder();
$listener = new ValuQuery\MongoDb\QueryListener();
$queryBuilder->getEventManager()->attach($listener);
Querying documents by ID:
$query = $queryBuilder->query('#5281d29b4c16801609000191');
Contents of $query
:
['query' => ['_id' => new MongoID('5281d29b4c16801609000191')]]
Querying documents by class:
$query = $queryBuilder->query('.video');
Contents of $query
:
['query' => ['classes' => ['$in' => ['video']]]]
Find second document, where name begins with "John" in ascending order:
$query = $queryBuilder->query('[name^="John"]:sort(age asc):limit(1):skip(1)');
Contents of $query
:
[
'query' => ['name' => new MongoRegex("/^John/")],
'sort' => ["age" => 1],
'limit' => 1,
'skip' => 1
]
It is easiest to use ValuQuery with ODM by integrating it to DocumentRepository by extending ValuQuery\DoctrineMongoOdm\DocumentRepository
. The class provides convenient methods query
, queryOne
, count
and exists
. If you don't want to use DocumentRepository, you should use QueryHelper
, which provides the same methods. Actually, DocumentRepository uses QueryHelper internally.
Set up your custom repository by extending ValuQuery\DoctrineMongoOdm\DocumentRepository
:
use ValuQuery\DoctrineMongoOdm\DocumentRepository;
class FileRepository extends DocumentRepository
{
//...
}
Now you can use your repository to perform CSS based queries and more!
Imagine, you want to fetch the titles of your hi-res videos:
$titles = $fileRepository->query('.video.hires', 'title');
Contents of $titles
:
['Best football scene HD', 'Super Holiday HD', 'In HD: amazing nature']