A Symfony2 Bundle who uses Google Custom Search API.
- Google Custom Search feature, see CSE
- PHP 5.4+
- Search engine ID (Creating a Custom Search Engine)
- API key that can be obtained from the Google Cloud Console
Package available on Packagist. Autoloading with Composer is PSR-0 compatible.
Let's suppose that you have a form with the input text 'search_term'. In your controller you can get the results after form submission like this:
<?php
...
use Carminato\GoogleCseBundle\Service\ApiRequest;
use Carminato\GoogleCseBundle\Service\Query\ApiQuery;
class SearchController extends Controller
{
...
public function searchAction(Request $request)
{
$filter = $this->createForm(new SearchFilterType());
$filter->bind($request);
if ($filter->isValid()) {
$data = $filter->getData();
$apiQuery = new ApiQuery(
array(
'key' => API_KEY,
'cx' => CX_KEY,
'q' => $data['search_term'],
'start' => 1,
'userIp' => $request->getClientIp()
)
);
$apiRequest = new ApiRequest($apiQuery);
$response = $apiRequest->getResponse();
if ($error = $response->getErrors()) {
return new Response($error->getMessage(), $error->getCode());
}
return array(
'results' => $response->getResults()
);
}
...
}
}
The results is an array containing CseApiResultItem objects.