2

On my project I use FOSElastica to filter many entities, then I use the same portion of code on many pages:

    $query = ('' !== $request->get('q') && null !== $request->get('q')) ? $request->get('q') : null;
    $teamId = ('' !== $request->get('team') && null !== $request->get('team')) ? $request->get('team') : $this->getUser()->getFavoriteTeam()->getId();
    $page = (0 < (int) $request->get('p')) ? $request->get('p') : 1;

    $repositoryManager = $this->get('fos_elastica.manager.orm');
    $repository = $repositoryManager->getRepository('AppBundle:BiologicalOriginCategory');
    $elasticQuery = $repository->searchByNameQuery($query, $page, $teamId, $this->getUser());
    $categoryList = $this->get('fos_elastica.finder.app.biologicalorigincategory')->find($elasticQuery);
    $nbResults = $this->get('fos_elastica.index.app.biologicalorigincategory')->count($elasticQuery);

    $nbPages = ceil($nbResults / BiologicalOriginCategory::NUM_ITEMS);

In the previous code the only things that changes: class used to filter, sometimes by team, sometimes by project, sometimes no filtering.

I would want avoid replication code by doing an IndexFilter util, then, I just call the IndexFilter service, give him: the class I want filter, the queryString, and the class(es) used to filter it.

It works well for the 6 first lines, because I can call it directly in my service.

But I don't know how I can dynamically call ElasticaBundle Finder and Index:

    $categoryList = $this->get('fos_elastica.finder.app.biologicalorigincategory')->find($elasticQuery);
    $nbResults = $this->get('fos_elastica.index.app.biologicalorigincategory')->count($elasticQuery);

I'm forced to inject it in the Service, but there is more than 10 entities, I can't inject 20 different other services each time and juste use 2 of them...

Are there a way to retrieve Finder and Index with the class name ? (AppBundle\Entity\BiologicalOriginCategory) ? I do it for retrieve the repository $repository = $repositoryManager->getRepository($class); and it works.

Thanks a lot for your help.

EDIT: I've maybe a solution to bypass the prolem, but not resolve it by using the fos_elastica.finder.app and fos_elastica.index.app. Then when I do a query, Elasticsearch do in on the whole index, and in my RepositoryMethod, I add a \Elastica\Query\Type() to filter results by Type.

I think it's less efficient than do a request whithout QueryType bu on the specific Type. No ?

mpiot
  • 1,482
  • 2
  • 15
  • 36

0 Answers0