I would like to use this code as a service so I don't have repeat this in every controller. How would I go about using this as a service so that it functions as below?
I've read some documentation and set it up as a service per below but am unsure how this is supposed to work to pass in the variables into the twig template.
Am currently accessing it as $search = $this->get("search")->search(); but am getting an error as I pass in 'search' => $search into the twig.
(ContextErrorException: Catchable Fatal Error: Argument 1 passed to Acme\ProjectBundle\Services\Search::search() must be an instance of Acme\ProjectBundle\Services\Request, none given, called in /var/www/html/Project/src/Acme/ProjectBundle/Controller/PageController.php on line 30 and defined in /var/www/html/Project/src/Acme/ProjectBundle/Services/Search.php line 8)
What is the proper way to do this and call it in the controller???
Original Index controller without the service
public function indexAction(Request $request)
{
// Search code
$results = null;
$query = $request->query->get('q');
if (!empty($query)) {
$em = $this->getDoctrine()->getManager();
$results = $em->createQueryBuilder()
->from('AcmeProjectBundle:Blog', 'b')
->select('b')
->where('b.title LIKE :search')
->setParameter(':search', "%${query}%")
->getQuery()
->getResult();
}
return $this->render('AcmeProjectBundle:Default:index.html.twig', array(
'query' => $query,
'results' => $results,
));
}
Service Search class
class Search
{
public function search(Request $request)
{
$results = null;
$query = $request->query->get('q');
if (!empty($query)) {
$em = $this->getDoctrine()->getManager();
$results = $em->createQueryBuilder()
->from('AcmeProjectBundle:Blog', 'b')
->select('b')
->where('b.title LIKE :search')
->setParameter(':search', "%${query}%")
->getQuery()
->getResult();
}
return array(
'query' => $query,
'results' => $results,
);
}
}
index.html.twig
{% block search %}
<form action="{{ path('acme_project_search') }}" method="GET">
<label><input type="search" name="q" value={{ query }}></label>
<input type="submit" value="Search">
</form>
<br>
{% endblock %}
config.yml
services:
search:
class: Acme\ProjectBundle\Services\Search