Check this code
class FooModel extends AppModel {
protected $_companyId = null;
public function setCompanyId($companyId) {
// Optional validation of the id here
$this->_companyId = $companyId;
}
public function beforeFind($query) {
if (!empty($this->_companyId)) {
$query['conditions'][$this->alias . '.company_id'] = $this->_companyId;
}
return $query;
}
}
To decouple it from the models I would suggest you to implement these two methods in a behavior and attach it to only the models that need it.
Edit, here as behavior:
class CompanyFilterBehavior extends ModelBehavior {
protected $_companyId = null;
public function setCompanyId(Model $Model, $companyId) {
// Optional validation of the id here
$this->_companyId = $companyId;
}
public function beforeFind(Model $Model, $query) {
if (!empty($this->_companyId)) {
$query['conditions'][$Model->alias . '.company_id'] = $this->_companyId;
}
return $query;
}
}
In your AppController you can do this:
public function beforeFilter() {
if ($this->User->loggedIn()
&& $this->{$this->modelClass}->Behaviors->loaded('CompanyFilter'))
{
$this->{$this->modelClass}->setCompanyId($this->Auth->user('company_id'));
}
}