• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
CI4 MVC DB accesses are often made in the controller in the examples

#1
Hello everybody.
I want to switch from CI3 to CI4.
The examples I find confuse me. Angry
If I understand correctly, database access should only take place in the model.
I'd like a minimal example of how it's done right. Smile
Controller, model and view with a "Select Where", an "Insert" and an "Update".
Thanks in advance
Ralf
Reply

#2
This is explained in the tutorial in the user guide:
http://codeigniter.com/user_guide/tutori...ction.html
http://codeigniter.com/user_guide/tutori...items.html

What do you find confusing?
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
Reply

#3
OK.
My English is not that good. So I guess I missed it or didn't understand it correctly. Idea
I have now got part of the transfer in CI4.
Then the rest is "just" hard work.
Many Thanks
Ralf
Reply

#4
(01-04-2021, 05:15 AM)includebeer Wrote: This is explained in the tutorial in the user guide:
http://codeigniter.com/user_guide/tutori...ction.html
http://codeigniter.com/user_guide/tutori...items.html

What do you find confusing?
In the tutorial, the "save" method is called in the "news" controller.
This is a database access and according to my understanding it should only take place in the "model".
Am I correct?

public function create()
{
$model = new NewsModel();

if ($this->request->getMethod() === 'post' && $this->validate([
            'title' => 'required|min_length[3]|max_length[255]',
            'body'  => 'required'
        ]))
{
$model->save([                   <------------------
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'body' => $this->request->getPost('body'),
]);

echo view('news/success');
}
else
{
echo view('templates/header', ['title' => 'Create a news item']);
echo view('news/create');
echo view('templates/footer');
}
}
Reply

#5
The save() function is part of the model and it’s OK to call it from the controller.
What is not recommended is making SQL queries outside of the model. It will work but it doesn’t follow the MVC pattern and your code will quickly become an unmaintainable mess.
If you need to build a custom SQL query, do it in a new function in the model, or at least in a library. Not in the controllers and not in the views.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.