Howdy.
I’ve spent a few hours searching for examples and recommendations but have yet to manage even the simplest code to move logic from my controller to my model. This is because all the examples I found relate to cake 3 (or even 2 about ModelApp and such).
So can someone throw me a bone here?!
For instance, the “business logic” of adding an article in the CMS example could be moved into a model - I know this is a simple example, but it would help to see it done.
https://book.cakephp.org/4/en/tutorials-and-examples/cms/authorization.html#fixing-the-add-edit-actions
What is there: -
// in src/Controller/ArticlesController.php
public function add()
{
$article = $this->Articles->newEmptyEntity();
$this->Authorization->authorize($article);
if ($this->request->is('post')) {
$article = $this->Articles->patchEntity($article, $this->request->getData());
// Changed: Set the user_id from the current user.
$article->user_id = $this->request->getAttribute('identity')->getIdentifier();
if ($this->Articles->save($article)) {
$this->Flash->success(__('Your article has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add your article.'));
}
$tags = $this->Articles->Tags->find('list');
$this->set(compact('article', 'tags'));
}
What I would like to be able to do (and I am guessing at the object names, function names, parameters… etc: -
// in src/Controller/ArticlesController.php
public function add()
{
$article = $this->Articles->newEmptyEntity();
$this->Authorization->authorize($article);
if ($this->request->is('post')) {
if ($this->Articles->articleAdd($article, $this->request->getData())) //business logic here!
{
$this->Flash->success(__('Your article has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add your article.'));
}
$tags = $this->Articles->Tags->find('list');
$this->set(compact('article', 'tags'));
}
//and in src/Model/Entity/ or is it a Behavior, or even in the Table? some function like
public function articleAdd($article = array(), $data = array())
{
...
thus you see how lost I am
Am I misunderstanding what is to go where here?
My actual need is sending an email when that add()
is('post')
fires.
I.e. Common mistake #3 here https://www.toptal.com/cakephp/most-common-cakephp-mistakes (which is for an older cake!).and itself could be wrong judging by the first comment after the article!
Any help appreciated!!
Cheers
Jonathan