Models, Views, and Controllers

1. Model

The Model represents the data and business logic of the application. It is responsible for interacting with the database, retrieving or manipulating data, and applying any business rules. In CodeIgniter, models are stored in the app/Models directory.

  • Purpose: Handle data operations (CRUD).
  • Example: Fetching user details, saving form inputs, or running queries.
namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $allowedFields = ['name', 'email', 'password'];
}

2. View

The View is the presentation layer, handling the user interface and displaying data to the user. It contains HTML, CSS, and minimal PHP for rendering dynamic content. Views are stored in the app/Views directory.

  • Purpose: Render the output to the browser.
  • Example: Showing user data or forms on a webpage.
<h1>Welcome, <?= $name; ?></h1>
<p>Your email is <?= $email; ?></p>

3. Controller

The Controller acts as the intermediary between the Model and the View. It handles user requests, processes input, communicates with the Model, and decides which View to load. Controllers are stored in the app/Controllers directory.

  • Purpose: Orchestrate the flow of data between the Model and View.
  • Example: Fetching data from the model and passing it to the view.
namespace App\Controllers;

use App\Models\UserModel;

class User extends BaseController
{
    public function profile($id)
    {
        $model = new UserModel();
        $data['user'] = $model->find($id);

        return view('profile', $data);
    }
}

Benefits of MVC in CodeIgniter

  • Separation of Concerns: Logic, data, and presentation are handled separately, making the code easier to understand and maintain.
  • Scalability: Allows adding new features with minimal impact on existing code.
  • Reusability: Models and Views can be reused across different parts of the application.

Share the Post:

Related Posts