Adding the Searchable behaviour to a Doctrine model in Symfony

The searchable behaviour within Doctrine is a brilliant and powerful way to add a quick and simple search to your symfony code. The basics of this behaviour are to create an index table for your given model, which contains 4 things, a keyword, the field it was in, the position and the object id it was in.

So how do we add this behaviour? We add it in the same way as the Timestampable behaviour, with one difference, we need to specify the fields we want to index.

       fields: [page_title, meta_description, meta_keywords, headline, sub_heading]
     Timestampable: ~
     page_title:       { type: string(255), notnull: true }
     meta_description: { type: string(255) }
     meta_keywords:    { type: string(255) }
     headline:         { type: string(255), notnull: true }
     sub_heading:      { type: string(255) }

Obviously you can pick any fields on your model to index, I just picked the meta details and headlines for now as that provided enough information for my simple search. Once you are happy with the fields you need to re-build your models to add the behaviour, and update your database structure to include the object_index table. This can be done with a symfony migration script if you already have a live database deployed.

To create the migrations scripts you need to run the doctrine:generate-migrations-diff which will create a file within [project root]/lib/migration/doctrine/

php symfony doctrine:generate-migrations-diff

To apply the migration changes from these scripts you need to run the doctrine:migrate command:

php symfony doctrine:migrate

This means that all future changes to your object will now be indexed. What you need to do is re-save any existing objects to auto-generate all the keywords, and I’ll explain that tomorrow.

One thought on “Adding the Searchable behaviour to a Doctrine model in Symfony”

  1. Hi Carl,
    Do you know a way to add the “Searchable” behavior to an entity using annotations instead of a yaml file? Google couldn’t tell me how to do it.

Leave a Reply

Your email address will not be published. Required fields are marked *