Database Integration

PHPFast makes it easy to work with databases. It has a Database class and built-in Drivers that help you connect to your database using Models and a query builder.

The database settings are stored in application/Config/Config.php, where you can easily change and manage different database connections.

Models

Models help you interact with the database easily. Each model represents a table in the database and provides methods to fetch, insert, update, and delete data.

By default, all models are stored in application/Models/.

Creating a Model

  • Go to application/Models/.

  • Create a new file, e.g., UsersModel.php.

  • Write the model code like this:

<?php

namespace App\Models;

use System\Core\BaseModel;

class UsersModel extends BaseModel {
    protected $table     = 'users';                 // Connects to the 'users' table
    protected $fillable  = ['username', 'email'];   // Columns that can be changed
    protected $guarded   = ['id', 'created_at'];    // Columns that should NOT be modified

    public function _schema() {
        return [
            'id'       => ['type' => 'int unsigned', 'auto_increment' => true, 'key' => 'primary'],
            'username' => ['type' => 'varchar(100)', 'null' => false],
            'email'    => ['type' => 'varchar(150)', 'null' => false]
        ];
    }
    
    public function getUsers($where = '', $params = [], $orderBy = 'id DESC', $page = 1, $limit = null){
        return $this->list($this->table, $where, $params, $orderBy, $page, $limit);
    }
    
    // Additional methods for custom queries
}

Changing the Database Driver

To switch between database drivers, update the db_driver setting in application/Config/Config.php

Using a Model in a Controller

After creating a model, you can use it in a controller to interact with the database.

Managing Database Schema

Each model includes a _schema() method that defines the structure of the database table it represents.

You can synchronize the model schema with the database using the command-line tool:

circle-exclamation

Last updated

Was this helpful?