Sometimes we need to create more than one callback functions in a model and change it by situation. For example, i have a recursive chained data as menu with fields id, parentId and title. when i need to create recursive menu array, i'll request for items which parentId is null and import child items on them with afterFind callback, but when i need to create breadcrumb, i'll request current menu item with id and import parents to data with afterFind callback. It would be great if there's a callback switch option instead of allow or disallow all callbacks. I wrote the ugly code below in my model for now but for the future projects it'd be great to have a callback switch function.
Thanks.
PHP Code:
protected $afterFind = ['includeParentData'];
protected $defaultAfterFind = [];
protected function includeSubData($data, $toParent = false){
$this->defaultAfterFind = $this->afterFind;
if(!$data['data']){$this->afterFind = $this->defaultAfterFind; return $data;}
if ($data['singleton']) {
$data['data'] = $this->setSubData($data['data']);
}else{
foreach ($data['data'] as &$item) {
$item = $this->setSubData($item);
}
}
$this->afterFind = $this->defaultAfterFind;
return $data;
}
protected function setSubData($data){
$data['_child'] = $this->setTempAfterFind($this->afterFind)->where(array('parent' => $data['id']))->find();
return $data;
}
protected function includeParentData($data, $toParent = false){
if(!$data['data']){return $data;}
if ($data['singleton']) {
$data['data'] = $this->setParentData($data['data']);
}else{
foreach ($data['data'] as &$item) {
$item = $this->setParentData($item);
}
}
return $data;
}
protected function setParentData($data){
if($data['parent']){
$data['_parent'] = $this->where(array('id' => $data['parent']))->first();
}
return $data;
}
public function setTempAfterFind(array $afterFind = []){
$this->afterFind = $afterFind;
return $this;
}