MilkCore

AbstractModel
in package

AbstractYes

Abstract Model Class

This is a base class for module data management. It provides basic CRUD operations, error handling, and methods for building complex queries. This class works with a single primary key and does not support multiple primary keys.

Tags
example
namespace Modules\BaseModule;
use MilkCore\AbstractModel;

!defined('MILK_DIR') && die(); // Prevent direct access

class BaseModuleModel extends AbstractModel
{
    public string $table = '#__base_module';
    public string $primary_key = 'id';
    public $object_class = 'BaseModuleObject';
}

Table of Contents

Properties

$last_error  : string
Last error message

Methods

__construct()  : mixed
Constructor
add_filter()  : void
Add a filter function
apply_edit_rules()  : object
Apply edit rules to a record
build_table()  : bool
Create or update the database table
clear_cache()  : void
Clear the results cache
delete()  : bool
Delete a record
drop_table()  : bool
execute()  : array<string|int, mixed>
Execute the current query and return raw results
filter_search()  : void
Filter search results
first()  : object|null
Get the first result from the current query
from()  : self
Add a FROM clause to the current query
get()  : array<string|int, mixed>
Execute the current query and return results as objects
get_all()  : array<string|int, mixed>
Get all data without limits
get_by_id()  : object|null
Get a record by its primary key
get_by_id_for_edit()  : object
Get a record for editing
get_by_id_or_empty()  : object
Get a record by ID or return an empty object
get_columns()  : mixed
get_empty()  : object
Get an empty object
get_filtered_columns()  : array<string|int, mixed>
Filtra i dati in base alle proprietà dell'oggetto se specificato
get_last_error()  : string
Get the last error message
get_last_insert_id()  : int
get_one()  : object|null
Execute the current query and return a single object
get_primary_key()  : string
group()  : self
Add a GROUP BY clause to the current query
has_error()  : bool
Check if an error occurred
limit()  : self
Add a LIMIT clause to the current query
order()  : self
Add an ORDER BY clause to the current query
reset_query()  : void
Reset the current query
save()  : bool|int
Save or update a record
select()  : self
Add a SELECT clause to the current query
set_query_params()  : void
Set query parameters from request
total()  : int
Get the total count of records
validate()  : bool
Validate data
where()  : self
Add a WHERE clause to the current query

Properties

$last_error

Last error message

public string $last_error = ''

Contains the last error message that occurred during an operation

Methods

__construct()

Constructor

public __construct([null|MySql|SQLite $db = null ]) : mixed

Initializes the model with a database connection and sets up the object class

Parameters
$db : null|MySql|SQLite = null

Optional database instance to use

add_filter()

Add a filter function

public add_filter(string $filter_type, callable $fn) : void

Adds a filter function to be used when filtering query results

Parameters
$filter_type : string

The type of filter

$fn : callable

The filter function

apply_edit_rules()

Apply edit rules to a record

public apply_edit_rules(object $data) : object

Applies edit rules defined in the object class to a record

Parameters
$data : object

The record object

Return values
object

The record object with edit rules applied

build_table()

Create or update the database table

public build_table([mixed $force_update = true ]) : bool

This method should be overridden in child classes because the prefix is not set during installation. If using an object model, this is already handled automatically.

Parameters
$force_update : mixed = true
Tags
example
// Using Schema for table management
public function build_table(): bool {
    $this->db->prefix = Config::get('prefix');
    $schema = Get::schema($this->table);
    $schema->id()
           ->string('title')
           ->text('description')
           ->datetime('created_at')
           ->datetime('updated_at', true);

    if ($schema->exists()) {
        return $schema->modify();
    } else {
        return $schema->create();
    }
}
Return values
bool

True if the table was created/updated successfully, false otherwise

clear_cache()

Clear the results cache

public clear_cache() : void

Empties the cache of query results

Tags
example
$this->model->clear_cache();

delete()

Delete a record

public delete(mixed $id) : bool

Deletes a record from the database

Parameters
$id : mixed

Primary key of the record to delete

Tags
example
if ($this->model->delete($id)) {
    return true;
} else {
    MessagesHandler::add_error($this->model->get_last_error());
    return false;
}
Return values
bool

True if deletion was successful, false otherwise

execute()

Execute the current query and return raw results

public execute([string $query = null ][, array<string|int, mixed> $params = [] ]) : array<string|int, mixed>
Parameters
$query : string = null

The SQL query to execute

$params : array<string|int, mixed> = []

Parameters to pass to the query to prevent SQL injection

Tags
example
$this->model->select('id, title')->where('status = ?', ['published'])->execute();
// or
$this->model->execute('SELECT * FROM posts');
// RETURN array of associative raw results
Return values
array<string|int, mixed>

An array of associative raw results representing the query results

Filter search results

public filter_search(string $search) : void

Adds search conditions to the current query This was moved from modellist because all query-related functionality should be in the model

Parameters
$search : string

The search term

first()

Get the first result from the current query

public first([string $query = null ][, array<string|int, mixed> $params = [] ]) : object|null

Executes the current query and returns a single object

Parameters
$query : string = null

The SQL query to execute

$params : array<string|int, mixed> = []

Parameters to pass to the query to prevent SQL injection

Tags
example
$post = $this->model->first('SELECT * FROM posts WHERE status = ?', ['published']);
// or
$post = $this->model->select('id, title')->where('status = ?', ['published'])->first();
Return values
object|null

The first record as an object or null if no records found

from()

Add a FROM clause to the current query

public from(string $from) : self
Parameters
$from : string

The table or join to query

Tags
example
$this->model->from('posts')->get();
$this->model->from('posts LEFT JOIN users ON posts.user_id = user.id')->get();
Return values
self

Returns the current instance for method chaining

get()

Execute the current query and return results as objects

public get([string $query = null ][, array<string|int, mixed> $params = [] ]) : array<string|int, mixed>
Parameters
$query : string = null

The SQL query to execute

$params : array<string|int, mixed> = []

Parameters to pass to the query to prevent SQL injection

Tags
example
$this->model->get('SELECT * FROM posts WHERE status = ?', ['published']);
// or
$this->model->select('id, title')->where('status = ?', ['published'])->get();
Return values
array<string|int, mixed>

An array of objects (instances of the class specified in $object_class)

get_all()

Get all data without limits

public get_all() : array<string|int, mixed>

Executes the current query without limits to retrieve all data

Tags
example
$posts = $this->model->get_all();
foreach ($posts as $post) {
    echo $post->title;
}
Return values
array<string|int, mixed>

An array of objects (instances of the class specified in $object_class)

get_by_id()

Get a record by its primary key

public get_by_id(mixed $id[, bool $use_cache = true ]) : object|null

Retrieves a record from the database using its primary key value

Parameters
$id : mixed

The primary key value

$use_cache : bool = true

Whether to use cache for data retrieval

Tags
example
$post = $this->model->get_by_id(123);
if ($post) {
    echo $post->title;
}
Return values
object|null

The record object or null if not found

get_by_id_for_edit()

Get a record for editing

public get_by_id_for_edit(mixed $id[, array<string|int, mixed> $merge_data = [] ]) : object

Retrieves a record for editing, applying edit rules

Parameters
$id : mixed

The primary key value

$merge_data : array<string|int, mixed> = []

Additional data to merge with the record

Tags
example
$data = $this->model->get_by_id_for_edit($id, Route::get_session_data());
if ($data === null) {
    Route::redirect_error('?page='.$this->page."&action=list", 'Invalid id');
}
Return values
object

The record object with edit rules applied

get_by_id_or_empty()

Get a record by ID or return an empty object

public get_by_id_or_empty(mixed $id[, array<string|int, mixed> $merge_data = [] ]) : object

Returns a record by its primary key, or an empty object if not found

Parameters
$id : mixed

The primary key value

$merge_data : array<string|int, mixed> = []

Optional data to merge with the record

Tags
example
$post = $this->model->get_by_id_or_empty(123);
echo $post->title; // No need to check if $post exists
Return values
object

The record object or an empty object

get_empty()

Get an empty object

public get_empty([array<string|int, mixed> $data = [] ]) : object

Returns an empty object of the associated class

Parameters
$data : array<string|int, mixed> = []

Data to initialize the object with

Tags
example
$new_post = $this->model->get_empty();
$new_post->title = "New Title";
Return values
object

An empty object of the associated class

get_filtered_columns()

Filtra i dati in base alle proprietà dell'oggetto se specificato

public get_filtered_columns([mixed $key = '' ][, mixed $value = '' ]) : array<string|int, mixed>
Parameters
$key : mixed = ''
$value : mixed = ''
Return values
array<string|int, mixed>

get_last_error()

Get the last error message

public get_last_error() : string

Returns the last error message that occurred

Tags
example
echo $this->model->get_last_error();
Return values
string

The last error message

get_one()

Execute the current query and return a single object

public get_one([string $query = null ][, array<string|int, mixed> $params = [] ]) : object|null
Parameters
$query : string = null

The SQL query to execute

$params : array<string|int, mixed> = []

Parameters to pass to the query to prevent SQL injection

Tags
example
$this->model->select('id, title')->where('status = ?', ['published'])->get_one();
// or
$this->model->get_one('SELECT id, title FROM posts WHERE status = ?', ['published']);
Return values
object|null

The first record as an object or null if no records found

group()

Add a GROUP BY clause to the current query

public group(string $group) : self
Parameters
$group : string

The field to group results by

Tags
example
$this->model->select('COUNT(*), user_id')->group('user_id')->get();
Return values
self

Returns the current instance for method chaining

has_error()

Check if an error occurred

public has_error() : bool

Checks if an error occurred during the last database operation

Tags
example
if ($this->model->has_error()) {
    echo "An error occurred: ".$this->model->get_last_error();
}
Return values
bool

True if an error occurred, false otherwise

limit()

Add a LIMIT clause to the current query

public limit(int $start[, int $limit = -1 ]) : self
Parameters
$start : int

Number of records to skip or number of recods if $limit is -1

$limit : int = -1

Number of records to retrieve

Tags
example
$this->model->limit(10, 10)->get();
Return values
self

Returns the current instance for method chaining

order()

Add an ORDER BY clause to the current query

public order([string|array<string|int, mixed> $field = '' ][, string $dir = 'asc' ]) : self
Parameters
$field : string|array<string|int, mixed> = ''

Field or array of fields to order by

$dir : string = 'asc'

Direction of ordering ('asc' or 'desc')

Tags
example
$this->model->order('title', 'desc')->get();
Return values
self

Returns the current instance for method chaining

reset_query()

Reset the current query

public reset_query() : void

Resets the current query and stores it as the last query

save()

Save or update a record

public save(array<string|int, mixed> $data[, mixed $id = null ]) : bool|int

Saves or updates a record in the database

Parameters
$data : array<string|int, mixed>

Data to save

$id : mixed = null

Primary key for update, If null the primary key will be used from the data array

Tags
example
$data_to_save = ['title' => 'Updated title', 'content' => 'New content'];
$result = $this->model->save($data_to_save, 123);
if($result) {
    echo "Save success";
} else {
    echo "Save Error: ".$this->model->last_error;
}
Return values
bool|int

False on error, otherwise the ID of the inserted/updated record

select()

Add a SELECT clause to the current query

public select(array<string|int, mixed>|string $fields) : self
Parameters
$fields : array<string|int, mixed>|string

Fields to select

Tags
example
$this->model->select('id, title')->get();
$this->model->select(['id', 'title'])->get();
Return values
self

Returns the current instance for method chaining

set_query_params()

Set query parameters from request

public set_query_params(array<string|int, mixed> $request) : void

Sets query parameters (limit, order, filter) from the request

Parameters
$request : array<string|int, mixed>

The request from the browser

Tags
example
$request = $this->get_request_params('table_posts');
$this->model->set_query_params($request);

total()

Get the total count of records

public total() : int

Executes the current query or the last executed query and returns the total number of records without limitations

Tags
example
$total_posts = $this->model->total();
echo "Total posts: " . $total_posts;
Return values
int

The total number of records

validate()

Validate data

public validate(array<string|int, mixed> $data) : bool

Performs validation on the data and returns true or false based on the validation result

Parameters
$data : array<string|int, mixed>

Data to validate

Return values
bool

True if validation passes, false otherwise

where()

Add a WHERE clause to the current query

public where(string $condition[, array<string|int, mixed> $params = [] ]) : self
Parameters
$condition : string

The SQL condition to add to the WHERE clause

$params : array<string|int, mixed> = []

Parameters to pass to the query to prevent SQL injection

Tags
example
$this->model->where('title LIKE ?', ['%test%'])->get();
Return values
self

Returns the current instance for method chaining


        
On this page

Search results