Models

Introduction

Model - This component is responsible for the data and also defines the structure of the application.

The model is the component responsible for working with application data. A model represents business logic, stores data, and makes it accessible from a controller or view.

In the context of web applications, the model can interact with the database, provide data validation, and execute and process business rules. The model may also include methods for reading, writing, updating, and deleting data from the database.

Using a model in MVC allows you to separate business logic from data display and user input. This makes the application easier to maintain and extend, reduces component coupling, and makes the code more readable and maintainable.

By default, all of the models for your application are stored in the app/models/ directory.

Using

In this example, we access the Users table to get all the records from it.

// app/models/User.php
namespace App\Models;

use Ghosty\Framework\Support\Facades\DB;
use PDO;

class User
{
    public function all()
    {
        return DB::getPDO()
            ->query('SELECT * FROM `users`')
            ->fetchAll(PDO::FETCH_ASSOC);
    }
}

You can also initialize the class object in your controller.

// app/controllers/UserController.php
namespace App\Controllers;

use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $User = new User;

        $Users = $User->all();

        print_r($Users);
    }
}