I have a number of functions in my controller logic and for every one I have some logic that pulls data for a “featured” set of units. These units are on several pages. How do I go about making this one piece of logic available to all 4 of the views that need it?
For reference, here is part of my controller logic:
public function index() {
$this->set('title', 'All accommodations available in and near Gulf Shores, AL');
$this->Unit->Behaviors->attach('Containable');
$this->Unit->contain(
array(
'User'=>array(
'id'),
'Location',
'Complex'=>array('location_id'),
'Image'=>array(
'logo','img1'
)
)
);
$c=$this->Unit->find('all',
array(
'limit'=>3,
'conditions'=>array(
'active'=>1,
'featured'=>1
)
)
);
$this->set('featured', $c);
$this->paginate['Unit']=array(
'limit'=>9,
'order' => 'RAND()',
'contain'=>array(
'User'=>array('email'),
'Complex'=>array('location_id','complex_website'),
'Location',
'Image'
),
'conditions'=>array(
'Unit.active'=>1)
);
$data = $this->paginate('Unit');
$this->set('allaccommodations', $data);
}
public function houses() {
$this->set('title', 'Home rentals available in Gulf Shores');
$this->Unit->Behaviors->attach('Containable');
$this->Unit->contain(
array(
'User'=>array(
'id'),
'Location',
'Complex'=>array('location_id'),
'Image'=>array(
'logo','img1'
)
)
);
$c=$this->Unit->find('all',
array(
'limit'=>3,
'conditions'=>array(
'active'=>1,
'featured'=>1
)
)
);
$this->set('featured', $c);
$this->paginate['Unit']=array(
'limit'=>9,
'order' => 'RAND()',
'contain'=>array(
'User'=>array('email'),
'Location',
'Image'
),
'conditions'=>array(
'Unit.type'=>array('house', 'rentalco'),
'Unit.active'=>1)
);
$data = $this->paginate('Unit');
$this->set('allhouses', $data);
}
...
I have two other functions that set a ‘featured’ variable that is available to the view. I’m sure there is a much better/more efficient way to do this?
Yes, the idea is to have all the data interaction in your model and have your controller clear and easy to follow. Fat models, skinny controllers. There are custom finds you can use: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#creating-custom-find-types
but I prefer to just make a model function because they’re easier to work with in the IDE with code completion and documentation. So for the featured find you keep using you could do something in your Unit model like:
Then in the UnitController: