CakePHP: Use Component In Model

I know it would make some Cake purists cringe, but I had to use a Component in a Model.

I wanted to use a component called ‘Geocoder’ in a model called ‘Address’.

In order for this to work, the controller that calls the function in Address must use the desired Component. Because I wanted to use the Geocoder component’s function in my beforeSave, I wanted to make sure that the call will work from every controller, and therefore added ‘Geocoder’ to the $uses in my custom app_controller.php, i.e:

<?php
class AppController extends Controller
{
    public $components = array('Auth', 'Session', 'GeoCoder');
 
}
?>

Then, in my beforeSave function of my Address model I call the geocode method of my Geocoder component as follows, after using App::import and instantiating the component by its full name. It looked something like this:

function beforeSave()
{
   App::import('Component','GeoCoder');
   $gc = new GeoCoderComponent();
   $this->data['geocoded'] = $gc->geocode($this->data['address']);
   return true;
}

Leave a Reply

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