VELOX API Docs

Model extends Element
in package

An abstract class that serves as a base model that can be extended to create models.

Example:

// Attributes has to match the attribute name (column name) unless otherwise specified.

// creating/manipulating models
$model = new Model(); // set attributes later via setters or public assignment.
$model = new Model(['attribute_name' => $value]);
$model->get('attribute_name');
$model->set('attribute_name', $value);
$model->getAttributeName(); // case will be changed to 'snake_case' automatically.
$model->setAttributeName($value); // case will be changed to 'snake_case' automatically.
$model->anotherAttribute; // case will be changed to 'snake_case' automatically.
$model->anotherAttribute = $value; // case will be changed to 'snake_case' automatically.
$attributes = $model->getAttributes(); // returns all attributes.
$model->save(); // persists the model in the database.
$model->update(['attribute_name' => $value]); // updates the model and save changes in the database.
$model->delete(); // deletes the model from the database.
Model::create($attributes); // creates a new model instance, call save() on the instance to save it in the database.
Model::destroy($id); // destroys a model and deletes it from the database.

// fetching models
$model = Model::first();
$model = Model::last();
$model = Model::one();
$models = Model::all(['name' => 'John'], 'age DESC', $offset, $limit);
$count = Model::count(); // returns the number of models in the database.
$model = Model::find($id); // $id is the primary key of the model.
$models = Model::find('age', 27, 'name', 'John', ...); // or Model::find(['name' => $value]);
$models = Model::findByName('John'); // fetches using an attribute, case will be changed to 'snake_case' automatically.
$models = Model::where('name', '=', $name); // fetches using a where clause condition.
$models = Model::where('name', 'LIKE', 'John%', [['AND', 'age', '>', 27], ...], 'age DESC', $limit, $offset);
$models = Model::fetch('SELECT * FROM @table WHERE `name` = ?', [$name]); // fetches using raw SQL query.
Tags
since
1.3.0

Table of Contents

$attributeName*  : mixed
$attributes  : array<string|int, mixed>
Model attributes. Corresponds to table columns.
$columns  : array<string|int, mixed>|null
Model table columns. If not set, the model will fall back to the default primary key `['id']`.
$database  : Database|null
The database instance/connection.
$primaryKey  : string|null
Model table primary key. If not set, `id` will be used by default.
$table  : string|null
Model table name. If not set, an auto-generated name will be used instead.
__call()  : mixed
Defines magic getters, setters, and finders for model attributes.
__clone()  : mixed
Makes the model safely cloneable via the `clone` keyword.
__construct()  : mixed
Class constructor.
__debugInfo()  : mixed
Makes the model more friendly presented when exported via `var_dump()`.
__get()  : mixed
Makes attributes accessible via public property access notation.
__isset()  : mixed
Makes attributes consumable via `isset()`.
__set()  : mixed
Makes attributes accessible via public property assignment notation.
__sleep()  : mixed
Makes the model safely consumable via `serialize()`.
__toString()  : mixed
Makes the object quickly available as a JSON string.
__unset()  : mixed
Makes attributes consumable via `unset()`.
all()  : array<string|int, static>|array<string|int, mixed>
Fetches all models.
count()  : int
Returns the count of models matching the passed condition (counting is done on the SQL end for better performance).
create()  : static
Creates an instance of the model. The model is not saved to the database unless `self::save()` is called.
delete()  : int
Deletes the model from the database.
destroy()  : int
Destroys (deletes) a model from the database if it exists.
fetch()  : array<string|int, static>|array<string|int, array<string|int, mixed>>
Executes a query (a prepared statement) and returns the result.
find()  : static|array<string|int, static>|null|array<string|int, mixed>
Finds a single or multiple models matching the passed condition.
findBySomeAttribute()  :
first()  : static|null
Fetches the first model object.
get()  : mixed
Gets the specified model attribute.
getAttributes()  : array<string|int, mixed>
Gets all model attributes.
getColumns()  : array<string|int, mixed>
Returns model table columns and sets `static::$columns` with a default value and returns it if it's not set.
getDatabase()  : Database
Returns model database connection and sets `static::$database` with a default value if it's not set.
getIterator()  : Traversable
`IteratorAggregate::getIterator()` interface implementation.
getPrimaryKey()  : string
Returns model table primary key and sets `static::$primaryKey` with a default value and returns it if it's not set.
getSomeAttribute()  :
getTable()  : string
Returns model table name and sets `static::$table` with a default value and returns it if it's not set.
hydrate()  : array<string|int, static>
Hydrates models from an array of model attributes (row).
isMigrated()  : bool
Checks whether the model table is migrated to the database or not.
last()  : static|null
Fetches the last model object.
migrate()  : void
Migrates model table to the database.
offsetExists()  : bool
`ArrayAccess::offsetExists()` interface implementation.
offsetGet()  : mixed
`ArrayAccess::offsetGet()` interface implementation.
offsetSet()  : void
`ArrayAccess::offsetSet()` interface implementation.
offsetUnset()  : void
`ArrayAccess::offsetUnset()` interface implementation.
one()  : static|null
Fetches a single model object.
save()  : static
Creates/updates a model and saves it in database.
schema()  : string
The SQL code to create the model table from. Has to match `self::$table`, `self::$columns`, and `self::$primaryKey`.
set()  : $this
Sets the specified model attribute.
setAttributes()  : $this
Sets all or a subset of model attributes.
setSomeAttribute()  :
toArray()  : array<string|int, mixed>
Returns array representation of the model. All attributes will be converted to `camelCase` form.
toJson()  : string
Returns JSON representation of the model. All attributes will be converted to `camelCase` form.
update()  : static
Updates the given attributes of the model and saves them in the database.
where()  : array<string|int, static>|array<string|int, array<string|int, mixed>>
Finds a single or multiple models by the passed condition.
assertAttributeExists()  : void
Asserts that the model attribute name is valid.
bootstrap()  : void
Override this method to add your own bootstrap code to the modal.
buildNestedQuery()  : array<string|int, mixed>
Builds a nested query.
buildWhereClause()  : array<string|int, mixed>
validateCondition()  : array<string|int, mixed>
Validates the passed condition.
validateOperator()  : string
Validates the passed operator.

Properties

$attributeName*

public mixed $attributeName*

Public property for model attribute, (attribute_name -> attributeName).

$attributes

Model attributes. Corresponds to table columns.

protected array<string|int, mixed> $attributes

$columns

Model table columns. If not set, the model will fall back to the default primary key `['id']`.

protected static array<string|int, mixed>|null $columns = ['id']

For good practice, keep the table columns in snake_case. Model attribute names match table columns.

$database

The database instance/connection.

protected static Database|null $database

$primaryKey

Model table primary key. If not set, `id` will be used by default.

protected static string|null $primaryKey = 'id'

$table

Model table name. If not set, an auto-generated name will be used instead.

protected static string|null $table = null

For good practice, keep the model name in singular form and make the table name in plural form.

Methods

__call()

Defines magic getters, setters, and finders for model attributes.

public __call(string $method, array<string|int, mixed> $arguments) : mixed

Examples: attribute_name has getAttributeName(), setAttributeName(), and findByAttributeName() methods.

Parameters
$method : string
$arguments : array<string|int, mixed>
Return values
mixed

__clone()

Makes the model safely cloneable via the `clone` keyword.

public __clone() : mixed
Return values
mixed

__construct()

Class constructor.

public __construct([array<string|int, mixed> $attributes = [] ]) : mixed

Keep all constructor arguments optional when extending the class. Or use self::bootstrap() instead.

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

[optional] The attributes to set on the model.

Return values
mixed

__debugInfo()

Makes the model more friendly presented when exported via `var_dump()`.

public __debugInfo() : mixed
Return values
mixed

__get()

Makes attributes accessible via public property access notation.

public __get(string $name) : mixed

Examples: model_id as $model->modelId

Parameters
$name : string
Return values
mixed

__isset()

Makes attributes consumable via `isset()`.

public __isset(string $name) : mixed
Parameters
$name : string
Return values
mixed

__set()

Makes attributes accessible via public property assignment notation.

public __set(string $name, mixed $value) : mixed

Examples: model_id as $model->modelId

Parameters
$name : string
$value : mixed
Return values
mixed

__sleep()

Makes the model safely consumable via `serialize()`.

public __sleep() : mixed
Return values
mixed

__toString()

Makes the object quickly available as a JSON string.

public __toString() : mixed
Return values
mixed

__unset()

Makes attributes consumable via `unset()`.

public __unset(string $name) : mixed
Parameters
$name : string
Return values
mixed

all()

Fetches all models.

public static all([array<string|int, mixed> $conditions = [] ][, string|null $order = null ][, int|null $limit = null ][, int|null $offset = null ]) : array<string|int, static>|array<string|int, mixed>
Parameters
$conditions : array<string|int, mixed> = []

Fetch conditions (like: ['id' => $id, ...]). Conditions are combined by logical AND.

$order : string|null = null

[optional] SQL order expression (like: id or id ASC).

$limit : int|null = null

[optional] To how many items the result should be limited.

$offset : int|null = null

[optional] From which item the result should start.

Return values
array<string|int, static>|array<string|int, mixed>

Examples:

  • PHP: Model::all(['name' => 'Doe', 'job' => 'Developer'],'age DESC', 3, 15).
  • SQL: SELECT * FROM `users` WHERE `name` = "Doe" AND `job` = `Developer` ORDER BY age DESC LIMIT 3 OFFSET 15.

count()

Returns the count of models matching the passed condition (counting is done on the SQL end for better performance).

public static count([array<string|int, mixed> $conditions = [] ]) : int
Parameters
$conditions : array<string|int, mixed> = []

[optional] Query conditions (like: ['id' => 1, ...]). Conditions are combined by logical AND.

Return values
int

create()

Creates an instance of the model. The model is not saved to the database unless `self::save()` is called.

public static create(array<string|int, mixed> $attributes) : static
Parameters
$attributes : array<string|int, mixed>

The attributes of the model.

Return values
static

delete()

Deletes the model from the database.

public delete() : int
Return values
int

The number of affected rows during the SQL operation.

destroy()

Destroys (deletes) a model from the database if it exists.

public static destroy(string|int $primaryKey) : int
Parameters
$primaryKey : string|int
Return values
int

The number of affected rows during the SQL operation.

fetch()

Executes a query (a prepared statement) and returns the result.

public static fetch(string $query[, array<string|int, mixed>|null $variables = [] ][, bool $raw = false ]) : array<string|int, static>|array<string|int, array<string|int, mixed>>
Parameters
$query : string

The query to execute. The @table can be used to inject the current model table name into the query.

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

[optional] The variables needed for the query.

$raw : bool = false

[optional] Whether fetch the models as arrays (raw) or as hydrated objects.

Tags
throws
BadMethodCallException

If called in an abstract class context.

Example:

  • Model::fetch('SELECT * FROM `users` WHERE `name` = :name OR `age` = :age', ['name' => 'Doe', 'age' => 27], true)
Return values
array<string|int, static>|array<string|int, array<string|int, mixed>>

The result as an array of objects or array of arrays depending on the passed parameters.

find()

Finds a single or multiple models matching the passed condition.

public static find(mixed|array<string|int, mixed> ...$condition) : static|array<string|int, static>|null|array<string|int, mixed>
Parameters
$condition : mixed|array<string|int, mixed>

Can either be the primary key or a set of condition(s) (like: id, or 'name', 'Doe', 'age', 35, or ['name' => $name]).

Return values
static|array<string|int, static>|null|array<string|int, mixed>

Depends on the number of conditions (1 = single, >1 = multiple).

Examples:

  • Find by primary key (ID): Model::find(1).
  • Find by specific value: Model::find('name', 'Doe', 'age', 35, ...) or Model::find(['name' => $name, 'age' => 35], ...).

findBySomeAttribute()

public findBySomeAttribute(mixed $value) :

Finder by model attribute, (attribute_name -> findByAttributeName($value)).

Parameters
$value : mixed
Return values

first()

Fetches the first model object.

public static first() : static|null
Return values
static|null

Examples: Model::first().

get()

Gets the specified model attribute.

public get(string $name) : mixed
Parameters
$name : string

Attribute name as specified in $columns.

Tags
throws
OutOfBoundsException

If the attribute does not exists.

Return values
mixed

Attribute value.

getAttributes()

Gets all model attributes.

public getAttributes() : array<string|int, mixed>
Return values
array<string|int, mixed>

Model attributes.

getColumns()

Returns model table columns and sets `static::$columns` with a default value and returns it if it's not set.

public static getColumns() : array<string|int, mixed>
Return values
array<string|int, mixed>

getDatabase()

Returns model database connection and sets `static::$database` with a default value if it's not set.

public static getDatabase() : Database
Return values
Database

getIterator()

`IteratorAggregate::getIterator()` interface implementation.

public getIterator() : Traversable
Return values
Traversable

getPrimaryKey()

Returns model table primary key and sets `static::$primaryKey` with a default value and returns it if it's not set.

public static getPrimaryKey() : string
Return values
string

getSomeAttribute()

public getSomeAttribute() :

Getter for model attribute, (attribute_name -> getAttributeName()).

Return values

getTable()

Returns model table name and sets `static::$table` with a default value and returns it if it's not set.

public static getTable() : string
Return values
string

hydrate()

Hydrates models from an array of model attributes (row).

public static hydrate(array<string|int, mixed> $models) : array<string|int, static>
Parameters
$models : array<string|int, mixed>
Return values
array<string|int, static>

Array of hydrated objects.

Example:

  • Model::hydrate([$arrayOfModelAttributes, ...])

isMigrated()

Checks whether the model table is migrated to the database or not.

public static isMigrated() : bool

You can override this method and return always true to disable auto migration.

NOTE: For compatibility reasons, the return value of this method true if it fails to connect to the database.

Return values
bool

last()

Fetches the last model object.

public static last() : static|null
Return values
static|null

Example: Model::last().

migrate()

Migrates model table to the database.

public final static migrate() : void
Tags
throws
BadMethodCallException

If called in an abstract class context.

Return values
void

offsetExists()

`ArrayAccess::offsetExists()` interface implementation.

public offsetExists(mixed $offset) : bool
Parameters
$offset : mixed
Return values
bool

offsetGet()

`ArrayAccess::offsetGet()` interface implementation.

public offsetGet(mixed $offset) : mixed
Parameters
$offset : mixed
Return values
mixed

offsetSet()

`ArrayAccess::offsetSet()` interface implementation.

public offsetSet(mixed $offset, mixed $value) : void
Parameters
$offset : mixed
$value : mixed
Return values
void

offsetUnset()

`ArrayAccess::offsetUnset()` interface implementation.

public offsetUnset(mixed $offset) : void
Parameters
$offset : mixed
Return values
void

one()

Fetches a single model object.

public static one([array<string|int, mixed> $conditions = [] ]) : static|null
Parameters
$conditions : array<string|int, mixed> = []

[optional] Query conditions (like: ['id' => 1, ...]). Conditions are combined by logical AND.

Return values
static|null

Examples:

  • Fetching the first items: Model::one().
  • Fetching an item according to a condition: Model::one(['name' => $name]).

save()

Creates/updates a model and saves it in database.

public save([array<string|int, mixed> $attributes = [] ]) : static
Parameters
$attributes : array<string|int, mixed> = []

Model attributes.

Return values
static

schema()

The SQL code to create the model table from. Has to match `self::$table`, `self::$columns`, and `self::$primaryKey`.

public abstract static schema() : string

Example: CREATE TABLE IF NOT EXISTS `table` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `text` VARCHAR(255));

Return values
string

set()

Sets the specified model attribute.

public set(string $name, mixed $value) : $this
Parameters
$name : string

Attribute name as specified in $columns.

$value : mixed

Attribute value.

Tags
throws
OutOfBoundsException

If the attribute does not exists.

Return values
$this

setAttributes()

Sets all or a subset of model attributes.

public setAttributes(array<string|int, mixed> $attributes) : $this
Parameters
$attributes : array<string|int, mixed>

Model attributes.

Return values
$this

setSomeAttribute()

public setSomeAttribute(mixed $value) :

Setter for model attribute, (attribute_name -> setAttributeName($value)).

Parameters
$value : mixed
Return values

toArray()

Returns array representation of the model. All attributes will be converted to `camelCase` form.

public toArray() : array<string|int, mixed>
Return values
array<string|int, mixed>

toJson()

Returns JSON representation of the model. All attributes will be converted to `camelCase` form.

public toJson() : string
Return values
string

update()

Updates the given attributes of the model and saves them in the database.

public update(array<string|int, mixed> $attributes) : static
Parameters
$attributes : array<string|int, mixed>

The attributes to update.

Return values
static

where()

Finds a single or multiple models by the passed condition.

public static where(string $column, string $operator, mixed $value[, array<string|int, array<string|int, mixed>> $additional = null ][, string|null $order = null ][, int|null $limit = null ][, int|null $offset = null ]) : array<string|int, static>|array<string|int, array<string|int, mixed>>
Parameters
$column : string

The column/attribute name.

$operator : string

Condition operator, can be: =, !=, <>, <, >, <=, >=, LIKE, NOT LIKE, IN, NOT IN.

$value : mixed

The value to compare to.

$additional : array<string|int, array<string|int, mixed>> = null

[optional] Additional conditions. Can be used to add more conditions to the WHERE clause. Deep nesting can be achieved by simply using a child array.

$order : string|null = null

[optional] SQL order expression (like: id or id ASC).

$limit : int|null = null

[optional] To how many items the result should be limited.

$offset : int|null = null

[optional] From which item the result should start.

Tags
throws
InvalidArgumentException

If operator is not supported or a condition is invalid.

throws
BadMethodCallException

If called in an abstract class context.

Examples:

  • Model::where('name', '=', 'Doe').
  • Model::where('age', '>', 27, [['AND', 'name', 'LIKE', 'Doe%'], $query, ..., [$subQuery, ...]], $order, $limit, $offset).
Return values
array<string|int, static>|array<string|int, array<string|int, mixed>>

assertAttributeExists()

Asserts that the model attribute name is valid.

protected static assertAttributeExists(mixed $name) : void
Parameters
$name : mixed

The name to validate.

Tags
throws
OutOfBoundsException

If attribute name is not a part of model $columns.

Return values
void

bootstrap()

Override this method to add your own bootstrap code to the modal.

protected bootstrap() : void
Return values
void

buildNestedQuery()

Builds a nested query.

private static buildNestedQuery(array<string|int, mixed> $condition, int|string $index) : array<string|int, mixed>
Parameters
$condition : array<string|int, mixed>

The condition in the form of ['OPERATOR1', 'COLUMN', 'OPERATOR2', 'VALUE', ], ..., [..., ...].

$index : int|string

The index of the condition.

Return values
array<string|int, mixed>

An associative array containing the SQL query and its needed variables.

buildWhereClause()

private static buildWhereClause(array<string|int, mixed> $conditions) : array<string|int, mixed>
Parameters
$conditions : array<string|int, mixed>
Return values
array<string|int, mixed>

validateCondition()

Validates the passed condition.

private static validateCondition(array<string|int, mixed> $condition, int|string $index) : array<string|int, mixed>
Parameters
$condition : array<string|int, mixed>

The condition to validate. in the form of ['OPERATOR1', 'COLUMN', 'OPERATOR2', 'VALUE']

$index : int|string

The index of the condition (used to make more user-friendly exception).

Tags
throws
InvalidArgumentException

If the condition is invalid.

Return values
array<string|int, mixed>

An array containing the validated condition.

validateOperator()

Validates the passed operator.

private static validateOperator(string $operator, int|string $index) : string
Parameters
$operator : string

The operator to validate.

$index : int|string

The index of the condition (used to make more user-friendly exception).

Tags
throws
InvalidArgumentException

If the operator is invalid.

Return values
string

The validated operator.

Search results