Wiki

Clone wiki

CakePHP Sphinx Behavior / Home

Welcome

First, you need Sphinx http://sphinxsearch.com/ installed and configured. I hope that you've already set up. Now, get the sphinxapi.php from the sphinx distribution and place it in app/vendors. Download the code and save it to app/models/behaviors/sphinx.php

Next, add code like this into your model

<?php  
class Film extends AppModel { 
var $actsAs = array('Sphinx'); 
} 
?>

Then, you can use sphinx in your controllers like this:

<?php
function index() 
{ 
    $sphinx = array('matchMode' => SPH_MATCH_ALL, 'sortMode' => array(SPH_SORT_EXTENDED => '@relevance DESC')); 
    $results = $this->Film->find('all', array('search' => 'search string here', 'sphinx' => $sphinx)); 
} 
?>

Or, a little bit more advanced setup:

<?php

function paging() 
{ 
        $pagination = array('Film' => array('contain' => 
                                       array('FilmType', 
                                             'Genre', 
                                             'FilmPicture' => array('conditions' => array('type' => 'smallposter')), 
                                             'Country', 
                                             'Person' => array('conditions' => array('FilmsPerson.profession_id' => array(1, 3, 4))),
                                             'MediaRating'), 
                                        'order' => array('Film.modified' => 'desc'), 
                                        'conditions' => array('Film.active' => 1), 
                                        'limit' => 30)); 
        $pagination['Film']['fields'] = array('Film.id', 'Film.imdb_rating', 'Film.title', 
                                              'Film.year', 'MediaRating.rating'); 


        $pagination['Film']['sphinx']['filter'][] = array('country_id', $this->params['named']['country']); 
        if (!empty($this->params['named']['search'])) 
        { 
            $search = trim($this->params['named']['search']); 

            $sort = ', modified DESC'; 
            if (!empty($this->params['named']['sort'])) 
            { 
                $sort = explode('.', $this->params['named']['sort']); 
                $sort = ', ' . $sort[1] . ' DESC'; 
            } 

            $pagination['Film']['sphinx']['matchMode'] = SPH_MATCH_ALL; 
            $pagination['Film']['sphinx']['sortMode'] = array(SPH_SORT_EXTENDED => '@relevance DESC' . $sort); 

            $pagination['Film']['search'] = $search; 
        } 
        $this->paginate = $pagination; 
        $films = $this->paginate(); 

} 
?>

Have fun!

Updated