Welcome Guest, Not a member yet? Register   Sign In
Controller and sql
#2

Yes, you technically can do that, but it's not recommended.

Controllers and Models are simply classes that are used to handle different things. Controllers should be responsible for controlling the flow from the request, getting the data together, and sending information back to the client.

A Model represents a single database table and has lots of built-in methods to make it easier to work with that table, including built-in functionality to handle the basic create, read, update, and delete methods as well as more advanced functionality.

The benefit of keeping them separate is a reuse of functionality. If you do the raw query in several controllers, and find that you need to change something, then you have to change it everywhere and not just in one place. There's 2 ways you could handle this using a model, the second option being the best long-term solution.

The "Raw Query" way:

PHP Code:
// In the controller
$users db_connect()
  ->
table('users')
  ->
where('role'$role)
  ->
get()
  ->
getResultArray(); 

First Option:

PHP Code:
// In the controller
$rows model('UserModel')
  ->
where('role'$role)
  ->
findAll(); 

This at least uses the model to pull the records (and is much more readable than the raw query method). It also makes it so that if you find you need to modify the records when you retrieve them and opt to use an afterFind event all places you grab that data will benefit without any extra work.

Second:

PHP Code:
// In the UserModel
public function getByRole(string $role)
{
  return 
$this
    
->where('role'$role)
    ->
findAll();
}

// In the controller
$users model(UserModel::class)->getByRole($role); 

This is the recommended solution for anything other than the simplest query. It isolates the actual query away from anyplace that needs the users. Where you need the users, you don't need to know how the users are pulled from the database to work. Now, if you change the way that roles are stored in the database (like pull it into a pivot table instead of hard-coded on the user table so that they can have more than one), you can handle that logic in one location in the model.
Reply


Messages In This Thread
Controller and sql - by lindaw - 01-26-2023, 08:12 AM
RE: Controller and sql - by kilishan - 01-26-2023, 03:17 PM
RE: Controller and sql - by lindaw - 01-27-2023, 02:09 PM
RE: Controller and sql - by InsiteFX - 01-26-2023, 10:20 PM



Theme © iAndrew 2016 - Forum software by © MyBB