williancarminato/google-cse-bundle

A Symfony2 Bundle who uses Google Custom Search API

dev-develop / 2.4.x-dev 2014-08-05 04:56 UTC

This package is not auto-updated.

Last update: 2024-03-26 02:07:46 UTC


README

A Symfony2 Bundle who uses Google Custom Search API.

Feature

  • Google Custom Search feature, see CSE

Requirements

Instalation

Package available on Packagist. Autoloading with Composer is PSR-0 compatible.

Usage

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.

Enjoy!