Welcome Guest, Not a member yet? Register   Sign In
Custom model methods
#1

Hey guys.
I'm working on a fairly new project, which is storing all setings in a MySQL table (myproject_settings). There are many cases where I need to fetch a single setting, using something like the following:
PHP Code:
$this->settings = new \App\Models\SettingsModel();

$mysetting $this->settings->where('name''mysetting')->first()->val

As you can see, having dozens of those lines throughout my project looks way too verbose. So I was thinking about adding a method to my model directly:
PHP Code:
class SettingsModel extends Model {
   ...

   public function getSetting($name) {
      return $this->where('name'$name)->first()->val;
   }


And then, in my controller, I could just do:
PHP Code:
$mysetting $this->settings->getSetting('mysetting'); 


My question is.. Is it bad practice to add custom methods directly in the model? I couldn't find anything related on the documentation.

Thank you.
Reply
#2

of course your can, its better
Reply
#3

(07-01-2021, 03:39 PM)Ryubal Wrote: My question is.. Is it bad practice to add custom methods directly in the model? I couldn't find anything related on the documentation.

On the contrary, writing reusable method is best practice. Having sql query all over the place is bad practice.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#4

Thank you, guys.
Today I was reading the docs again, and I found in the provided example that it actually encourages using methods inside the model (https://codeigniter4.github.io/userguide...ction.html)
Sorry for the ignorance, the doc is a bit messy  Smile
Reply
#5

thank you, i think i can start do the same
Reply
#6

that nice
Reply




Theme © iAndrew 2016 - Forum software by © MyBB