One of the most important tasks facing the development of the site is the implementation of full-text search. One of the popular and simple implementation options is to use Sphinx. On Habré there are already articles dedicated to him, but the Query Builder library is not deservedly mentioned. This is what I will try to fix.
Introduction
One of the most important tasks facing the development of the site is the implementation of full-text search. One of the popular and simple implementation options is to use Sphinx. On Habré there are already articles dedicated to him, but the Query Builder library is not deservedly mentioned. This is what I will try to fix.
This text is a free translation of the article
“SphinxQL Query Builder for PHP” .
')
Why is it worth using?
- Minimizing the risks of possible sql injection against your indexes;
- Makes your queries more readable and easier to maintain;
- Allows you to create more simple and flexible queries;
- It has all the functions implemented in the Sphinx API library and most of the functions used when working with SphinxQL;
- It has been tested in several versions of SphinxSearch and php.
How to install?
If you use Composer, then you can install it with the following command:
$ composer install foolz/sphinxql-query-builder --save
Or
clone it from the githab repository.
Comparison of approaches
An example without using Query Builder:
<?php $conn = new mysqli('localhost', null, null, null, 9306); if ($conn->connect_error) { throw new Exception('Connection Error: ['.$conn->connect_errno.'] '.$conn->connect_error, $conn->connect_errno); } $resource = $conn->query('SELECT * FROM anime_index WHERE MATCH(\'@character Asuka\') AND age BETWEEN 12 AND 19'); $results = array(); while ($row = $resource->fetch_assoc()) { $results[] = $row; } $resource->free_result();
And here is a piece of code using Query Builder:
<?php use Foolz\SphinxQL\Connection; use Foolz\SphinxQL\SphinxQL; $conn = new Connection(); $conn->setParams(array('host' => 'localhost', 'port' => 9306)); $query = SphinxQL::create($conn) ->select('*') ->from('anime_index') ->match('character', 'Asuka');
Isn’t it so much clearer and simpler?
Let's summarize a little
Although we can write queries using MySQLi, Query Builder allows us to write more understandable and easily supported queries. I think the example above shows it very clearly. More examples and documentation on how to use the library can be found on the
githab .