Models

Models provide an easy way to interact with your database. The Mini Framework uses PDO for database operations and provides a simple ORM-like interface for common tasks.

Creating Models

Using CLI (Recommended)

php mini make:model User

This creates a model file at:

app/Models/User.php

Manual Creation


<?php

namespace App\Models;

use Core\Model;

class User extends Model
{
    // Optional: specify table name
    protected $table = 'users';
}

Table Names

By default, the framework automatically determines the table name from the model class name. It converts the class name to lowercase and adds an 's' (pluralizes).

Model Class Table Name
User users
Product products
Order orders

Custom Table Name


class User extends Model
{
    // Override default table name
    protected $table = 'my_users';
}

Database Configuration

Configure your database connection in config/database.php:


<?php
// .env
DB_NAME=mini_framework
DB_USER=root
DB_PASS=
⚠️ Security: Never commit database credentials to version control. Use environment variables or a .env file for production.

CRUD Operations

Create (Insert)


// Create a new user
$user = new User();
$userId = $user->create([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'password' => password_hash('secret', PASSWORD_DEFAULT)
]);

// Returns the ID of the newly created record

Read (Select)


// Get all users
$users = User::all();

// Find a user by ID
$user = User::find(1);

// Find with WHERE clause
$users = User::where('status', 'active')->get();
$user = User::where('email', 'john@example.com')->first();

Update


// Update a user
$user = new User();
$user->update(1, [
    'name' => 'Jane Doe',
    'email' => 'jane@example.com'
]);

Delete


// Delete a user
$user = new User();
$user->delete(1);

Complete Model Example


<?php

namespace App\Models;

use Core\Model;

class User extends Model
{
    // Optional: specify custom table name
    protected $table = 'users';

    /**
     * Get active users
     */
    public static function active()
    {
        return static::where('status', 'active')->get();
    }

    /**
     * Find user by email
     */
    public static function findByEmail($email)
    {
        return static::where('email', $email)->first();
    }

    /**
     * Create a new user with validation
     */
    public function createUser($data)
    {
        // Hash password if provided
        if (isset($data['password'])) {
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }
        
        // Set default values
        $data['created_at'] = date('Y-m-d H:i:s');
        
        return $this->create($data);
    }

    /**
     * Update user profile
     */
    public function updateProfile($id, $data)
    {
        // Remove password if not provided
        if (empty($data['password'])) {
            unset($data['password']);
        } else {
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }
        
        $data['updated_at'] = date('Y-m-d H:i:s');
        
        return $this->update($id, $data);
    }
}

Using Models in Controllers


<?php

namespace App\Controllers;

use Core\Controller;
use Core\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index(Request $request)
    {
        // Get all users
        $users = User::all();
        
        return $this->view('users.index', ['users' => $users]);
    }

    public function show(Request $request, $id)
    {
        // Find user by ID
        $user = User::find($id);
        
        if (!$user) {
            return $this->text('User not found', 404);
        }
        
        return $this->view('users.show', ['user' => $user]);
    }

    public function store(Request $request)
    {
        $data = $request->post();
        
        // Create new user
        $user = new User();
        $userId = $user->create($data);
        
        return $this->redirect('/users/' . $userId);
    }
}

Advanced Queries

For complex queries, you can access the PDO connection directly:


class User extends Model
{
    /**
     * Get users with custom query
     */
    public static function getActiveUsersWithPosts()
    {
        $model = new static();
        $stmt = $model->connection->query("
            SELECT u.*, COUNT(p.id) as post_count 
            FROM users u 
            LEFT JOIN posts p ON u.id = p.user_id 
            WHERE u.status = 'active' 
            GROUP BY u.id
        ");
        
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * Search users
     */
    public static function search($term)
    {
        $model = new static();
        $stmt = $model->connection->prepare("
            SELECT * FROM users 
            WHERE name LIKE ? OR email LIKE ?
        ");
        
        $searchTerm = \"%{$term}%\";
        $stmt->execute([$searchTerm, $searchTerm]);
        
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
}
💡 Tip: Always use prepared statements when including user input in queries to prevent SQL injection attacks. The framework's built-in methods handle this automatically.

Next Steps

Now that you understand models, learn about: