Welcome Guest, Not a member yet? Register   Sign In
better approach to work with models
#1

(This post was last modified: 07-01-2021, 11:23 AM by tino.)

this may seems a stupid question, and probably it is.
let's say i have to print all the users who are verificated, would be better doing something like this:
PHP Code:
class UserController extends BaseController {

    public function showEveryUser() {
        $userModel = new UserModel();

        $users $userModel->where("is_verificated"1)->findAll();

        ...
    }


or creating a specific method in the UserModel like this:
PHP Code:
class UserModel extends Model {

    public function getEveryUser() {
        return $this->where("is_verificated"1)->findAll();
    }


and then calling UserModel->getEveryUser() in UserController->showEveryUser()?
Reply
#2

There's no right or wrong answer. It depends on how you want to organize your application. Personally I prefer to have the least possible logic in the controllers and in the models. I prefer to keep them simple and put most of the logic in a library. If your application is super small, it may be overkill to do it this way. But if you have a somewhat big application, it's easier to develop and to maintain when the logic is not everywhere in the controllers, the models, etc. It's also easier to reuse those functions if you need them in multiple places in your code. You can see an example of this in my tutorial for a basic application.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#3

i dont do query on controller, all put in other class , more efficient (sometime same query need in different controller)
Reply
#4

(07-01-2021, 11:16 AM)tino Wrote: this may seems a stupid question, and probably it is.
let's say i have to print all the users who are verificated, would be better doing something like this:
PHP Code:
class UserController extends BaseController {

    public function showEveryUser() {
        $userModel = new UserModel();

        $users $userModel->where("is_verificated"1)->findAll();

        ...
    }


or creating a specific method in the UserModel like this:
PHP Code:
class UserModel extends Model {

    public function getEveryUser() {
        return $this->where("is_verificated"1)->findAll();
    }


and then calling UserModel->getEveryUser() in UserController->showEveryUser()?


In MVC format always use Queries in Model Section that is better practice. (We can reuse the code anywhere in the project by calling that particular model)
Reply
#5

I would personally also put it in a Model, running queries inside a controller is a no-go for me..
Reply
#6

(This post was last modified: 07-02-2021, 12:40 PM by tino.)

thanks for all the answers :)
Reply




Theme © iAndrew 2016 - Forum software by © MyBB