5.2-extending.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. require(__DIR__.'/init.php');
  3. use Solarium\Client;
  4. use Solarium\QueryType\Select\Query\Query as Select;
  5. htmlHeader();
  6. // This is a custom query class that could have some customized logic
  7. class MyQuery extends Select
  8. {
  9. // ...customization here...
  10. }
  11. // And this is the extended client, that modifies the default query mapping
  12. // for select queries to our custom query class.
  13. // BTW, the same could also be done using a plugin, see example 5.3.2
  14. class MyClient extends Client
  15. {
  16. /**
  17. * Querytype mappings
  18. */
  19. protected $queryTypes = array(
  20. self::QUERY_SELECT => array(
  21. 'query' => 'MyQuery',
  22. 'requestbuilder' => 'Solarium\QueryType\Select\RequestBuilder\RequestBuilder',
  23. 'responseparser' => 'Solarium\QueryType\Select\ResponseParser\ResponseParser'
  24. ),
  25. );
  26. }
  27. // create a client instance
  28. $client = new MyClient($config);
  29. // create a select query instance
  30. $query = $client->createSelect();
  31. // check the query class, it should be our custom query class
  32. echo 'Query class: ' . get_class($query) . '<br/>';
  33. // execute query
  34. $result = $client->execute($query);
  35. // display the total number of documents found by solr
  36. echo 'NumFound: '.$result->getNumFound();
  37. // show documents using the resultset iterator
  38. foreach ($result as $document) {
  39. echo '<hr/><table>';
  40. // the documents are also iterable, to get all fields
  41. foreach ($document as $field => $value) {
  42. // this converts multivalue fields to a comma-separated string
  43. if (is_array($value)) {
  44. $value = implode(', ', $value);
  45. }
  46. echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>';
  47. }
  48. echo '</table>';
  49. }
  50. htmlFooter();