BaseModel

__construct()

<?php
public function __construct() {
    $configdb = config('db');  // Use config from config.php with key 'db'
    $this->db = $this->loadDatabaseDriver($configdb['db_driver'], $configdb);
    unset($configdb);
}
  • Initializes the database connection using the configuration from the config file.

  • Loads the appropriate database driver.

_schema()

<?php
public function _schema() {
    return [];
}

Defines the structure of the model by returning a schema array. By default, it returns an empty array, but child classes can override this method to specify the model's data structure.

_table()

<?php
public function _table() {
    return $this->table;
}

Returns the name of the database table associated with the model. It helps establish the connection between the model and its corresponding table.

_columns()

<?php
protected function _columns() {
    return $this->fillable;
}

Returns the list of columns that are allowed to be filled with data. These columns are defined in the child model and determine which fields can be updated or inserted to prevent unauthorized modifications.

fill()

<?php
protected function fill($data) {}
  • Filters the input data to only include columns that are allowed to be filled.

  • $data: Data to filter.

row()

<?php
public function row($table, $where = '', $params = []) {}

Fetches a single row from the database based on the specified conditions.

$table: Name of the table.

$where: Query conditions.

$params: Optional parameters.

return: Data row or false if no result.

rowField()

<?php
public function rowField($table, $fields, $where = '', $params = []) {}

Fetches a single row with specific fields from the database based on the specified conditions.

$table: Name of the table.

$fields: Fields to query (optional).

$where: Query conditions.

$params: Optional parameters.

return: Data row or false if no result.

list()

<?php
public function list($table, $where = '', $params = [], $orderBy = '', $page = 1, $limit = null) {}

Fetches multiple rows from the database based on the specified conditions, order, and pagination.

$table: Name of the table.

$where: Query conditions.

$params: Optional parameters.

$orderBy: ORDER BY clause (optional).

$page: Page number for pagination.

$limit: Number of results per page (optional).

return: List of data rows.

listpaging()

<?php
public function listpaging($table, $where = '', $params = [], $orderBy = '', $page = 1, $limit = null) {}

Fetches multiple rows with pagination from the database based on the specified conditions, order, and pagination.

$table: Name of the table.

$where: Query conditions.

$params: Optional parameters.

$orderBy: ORDER BY clause (optional).

$page: Page number for pagination.

$limit: Number of results per page (optional).

return: List of data rows.

listfieldpaging()

<?php
public function listfieldpaging($table, $fields = '*', $where = '', $params = [], $orderBy = '', $page = 1, $limit = null) {}

Fetches multiple rows with specific fields and pagination from the database based on the specified conditions, order, and pagination.

$table: Name of the table.

$fields: Fields to fetch.

$where: Query conditions.

$params: Optional parameters.

$orderBy: ORDER BY clause (optional).

$page: Page number for pagination.

$limit: Number of results per page (optional).

return: List of data rows.

add()

<?php
public function add($table, $data) {}
  • Inserts a new row into the database.

$table: Name of the table.

$data: Data to insert.

return: Success or failure.

set()

<?php
public function set($table, $data, $where = '', $params = []) {}

Updates existing rows in the database based on the specified conditions.

$table: Name of the table.

$data: Data to update.

$where: Update conditions.

return: Number of affected rows.

del()

<?php
public function del($table, $where = '', $params = []) {}

Deletes rows from the database based on the specified conditions.

$table: Name of the table.

$where: Delete conditions.

return: Number of affected rows

query()

<?php
public function query($query, $params = []) {}

Executes a custom SQL query.

$query: The SQL query string.

$params: An array of parameters to bind to the query (optional).

return: Result of the query (used for SELECT, INSERT, UPDATE, DELETE)

lastInsertId()

<?php
public function lastInsertId() {}

Returns the ID of the last inserted row.

count()

<?php
public function count($table, $where = '', $params = []) {}

Counts the number of rows in the database based on the specified conditions.

$table: The name of the table.

$where: The WHERE clause to filter records (optional).

$params: An array of values corresponding to the parameters in the WHERE clause (optional).

return: Number of records in the table.

Example

UsersModel.php

Create UsersModel and add the following code:

<?php
namespace App\Models;
use System\Core\BaseModel;

class UsersModel extends BaseModel {
    protected $table = 'fast_users';
    protected $fillable = ['username', 'email', 'password', 'fullname'];
    protected $guarded = ['id', 'created_at', 'updated_at'];
    
    public function _schema() {
        return [
            'id'         => 'INT',
            'username'   => 'VARCHAR(255)',
            'email'      => 'VARCHAR(255)',
            'phone'      => 'VARCHAR(30)',
            'password'   => 'VARCHAR(255)',
            'created_at' => 'DATETIME',
            'updated_at' => 'DATETIME'
        ];
    }
    public function getUsers($where = '', $params = [], $orderBy = 'id DESC', $page = 1, $limit = null) {
        return $this->list($this->table, $where, $params, $orderBy, $page, $limit);
    }
    
    public function getUsersPage($where = '', $params = [], $orderBy = 'id DESC', $page = 1, $limit = null) {
        return $this->listpaging($this->table, $where, $params, $orderBy, $page, $limit);
    }
    
    public function getFieldUsersPage($fields = '', $where = '', $params = [], $orderBy = 'id DESC', $page = 1, $limit = null) {
        return $this->listfieldpaging($this->table, $fields, $where, $params, $orderBy, $page, $limit);
    }
    
    public function getUserById($id){
        return $this->row($this->table, 'id = ?', [$id]);
    }
    
    public function getUserByIdField($fields, $id){
        return $this->rowField($this->table, $fields, 'id = ?', [$id]);
    }

    public function getUserByUsername($username){
        return $this->row($this->table, 'username = ?', [$username]);
    }
    
    public function getUserByEmail($email){
        return $this->row($this->table, 'email = ?', [$email]);
    }
    
    public function addUser($data) {
        $data = $this->fill($data);
        return $this->add($this->table, $data);
    }
    
    public function updateUser($id, $data) {
        $data = $this->fill($data);
        return $this->set($this->table, $data, 'id = ?', [$id]);
    }
    
    public function deleteUser($id) {
        return $this->del($this->table, 'id = ?', [$id]);
    }
    
    public function searchUser($conditions = [])
    {
        $query = "SELECT * FROM " . $this->table;
        $params = [];

        if (!empty($conditions)) {
            $query .= " WHERE ";
            $whereClauses = [];

            foreach ($conditions as $field => $value) {
                $whereClauses[] = "$field LIKE ?";
                $params[] = '%' . $value . '%';
            }
            $query .= implode(' OR ', $whereClauses);
        }

        return $this->query($query, $params);
    }
    
}

UsersController.php

In UsersController.php, you can utilize UsersModel to interact with the database and seamlessly pass the retrieved data to the view for rendering.

<?php
namespace App\Controllers;
use System\Core\BaseController;

class UsersController extends BaseController {
        public function __construct()
    {
        load_helpers(['backend']);
        $this->usersModel = new UsersModel();
    }

    public function index() {
        $users = $this->usersModel->getUsers(); // Get all users

        // Render the view
        $this->data('users', $users);
        $this->render('backend', 'backend/users/index');
    }
    
    public function profile($id) {
        $info = $this->usersModel->getUserById($id); // Get user by ID

        // Render the view
        $this->data('info', $info);
        $this->render('backend', 'backend/users/profile');
    }
    
    public function register() {
        $input = [
            'username'          => S_POST('username') ?? '',
            'fullname'          => S_POST('fullname') ?? '',
            'email'             => S_POST('email') ?? '',
            'phone'             => S_POST('phone') ?? '',
            'password'          => S_POST('password') ?? '',
            'password_repeat'   => S_POST('password_repeat'),
        ]
        
        // Assume that the $input has been validated as valid.
        $user_id = $this->usersModel->addUser($input);

        // Assume that added user and $users_id has value
        Session::flash('success', 'Register Successfully!!!');
        $this->render('backend', 'backend/users/index');
    }
}

Last updated

Was this helpful?