Issue
I have been wondering about this before, I'll take my current application as an example.
In this application we have Users, Apps and a much of other models. All these models are modified normally, with add
, edit
and delete
actions. The point is the controller logic behind this is basically identical for each model. However, the model name is of course different everywhere.
Question: what is a proper way of reusing the standard controller actions for different models?
I know AppController
code is shared, so that would be a place to start. But then I can't figure out how to do the model selection properly.
An example of the core code of an edit
page would be:
$entity = $model->get($id);
$model->patchEntity($entity, $this->request->getData());
if ($model->save($entity))
//...
else
//...
$this->set(compact('entity'));
Solution
If you are following the CakePHP's naming conventions then follow this
In your AppController:-
$modelName = $this->name; //This will give you the model name
$model = $this->$modelName; //Instance of the model object
$model->find('all');
EDIT:-
Let us consider you have two controller
- ProductsController
2.CategoriesController -->//Both extends the AppController
And your add() is same for both the controller,
Then in your both ProductsController and CategoriesController
public function add(){
parent::add(); //this will call to the add() of AppController
}
Then in you AppController
public function add(){
$modelName = $this->name; //This will give you the model name
$modelObject = $this->$modelName;
$entity = $this->$modelObject->newEntity($this->request->data, ['validate' => false]);
$this->$modelObject->save($entity);
}
Answered By - bikash.bilz
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.