I always have bad time writing code for search in any new project. So, I decided to write a quick Searchable behavior in CakePHP so as to avoid doing it again and again in any project.
Please note: This only handles text based searches, and it's a very basic version, written in less than two hours.
Here's how it works:
-
In the model which you want to be searchable, just add:
-
Now in controller you can use function called Model::stringSearch()PHP:
-
// here your $keyword can be something like ‘nicole scherzinger’
-
Algorithm behind its functioning (inside Model::stringSearch()):
-
Search procedure 1: Consider $keywords as phrase, and fetch ids based on this phrase from the passed fields. So if you have passed on :
$keywords = 'nicole scherzinger';
$videos = $this->Video->stringSearch($keywords, array('title', 'description'));
It will be treated as "nicole scherzinger", the results returned here will be marked as highest relevant results.
- Search Procedure 2: Find 'nicole' and 'scherzinger' together in given fields. Relevancy --
- Search Procedure 3: Find 'nicole' or 'scherzinger'. Relevancy decreased again.
- Now it combines all the ids returned from all 3 types of searches, in the same order of their relevancy. Then fetches records using findAllbyId() and returns them to caller.
Download it here. Hope you people like it.
P.S. My girlfriend will be angry when she will see Nicole scherzinger here… So, if you're reading it, I'm sorry I was just working on this MP3 and Videos project, you know?? hehe
- Abhimanyu Grover
on Wed, 15 October, 2008 at 3:11 pm
Any thoughts on how you would paginate these results?
Any help would be greatly appreciated.
on Thu, 16 October, 2008 at 6:14 am
@matt It was just an experimental behavior, not for real use. I suggest you try this one:
http://bakery.cakephp.org/articles/view/search-feature-to-cakephp-blog-example
It also index the data for you.