PHP Класс atk4\data\Model

Наследование: implements ArrayAccess, implements IteratorAggregate, use trait atk4\core\ContainerTrait, use trait atk4\core\DynamicMethodTrait, use trait atk4\core\HookTrait, use trait atk4\core\InitializerTrait, use trait atk4\core\NameTrait
Показать файл Открыть проект Примеры использования класса

Открытые свойства

Свойство Тип Описание
$_default_class_addExpression string The class used by addField() method.
$_default_class_addField string The class used by addField() method.
$_default_class_hasMany string The class used by hasMany() method.
$_default_class_hasOne string The class used by hasOne() method.
$_default_class_join string The class used by join() method.
$_dirty_after_reload Save record.
$conditions array Conditions list several conditions that must be met by all the records in the associated DataSet. Conditions are stored as elements of array of 1 to 3. Use addCondition() to add new conditions.
$data array Avoid accessing $data directly, use set() / get() instead.
$dirty array If the value you set equal to the original value, then the key in this array will be removed. The $dirty data will be reset after you save() the data but it is still available to all before/after save handlers.
$id mixed Contains ID of the current record. If the value is null then the record is considered to be new.
$id_field string While in most cases your id field will be called 'id', sometimes you would want to use a different one or maybe don't create field at all.
$limit array Array of limit set.
$load_normalization boolean When set to true, loading model from database will also perform value normalization. Use this if you think that persistence may contain badly formatted data that may impact your business logic.
$only_fields false | array When you have used onlyFields() before loading the data for this model, then only that set of fields will be available. Attempt to access any other field will result in exception. This is to ensure that you do not accidentally access field that you have explicitly excluded. The default behavior is to return NULL and allow you to set new fields even if addField() was not used to set the field.
$order array Array of set order by.
$persistence Persistence Persistence driver inherited from atk4\data\Persistence.
$persistence_data array Persistence store some custom information in here that may be useful for them. The key is the name of persistence driver.
$reload_after_save boolean | null This is to ensure that any SQL-based calculation are executed and updated correctly after you have performed any modifications to the fields. You can set this property to "true" or "false" if you want to explicitly enable or disable reloading.
$strict_types boolean When set to true, all the field types will be enforced and normalized when setting.
$table string | array You can define this field as associative array where "key" is used as the name of persistence driver. Here is example for mysql and default: $table = ['user', 'mysql'=>'tbl_user'];
$title_field string $model->importRows(['Bananas','Oranges']); // 2 records imported

Защищенные свойства (Protected)

Свойство Тип Описание
$strict_field_check boolean In some situations you want to set field value and then declare it later, then set $strict_field_check = false, but it's not recommended.

Открытые методы

Метод Описание
__clone ( )
__construct ( Persistence | array $persistence = null, array $defaults = [] ) Creation of the new model can be done in two ways:.
__debugInfo ( ) : array Returns array with useful debug info for var_dump.
_init ( )
_unset ( string | array $name ) Remove current field value and use default.
action ( string $mode, array $args = [] ) : atk4\dsql\Query Execute action.
addCondition ( mixed $field, mixed $operator = null, mixed $value = null ) Narrow down data-set of the current model by applying additional condition. There is no way to remove condition once added, so if you need - clone model.
addExpression ( string $name, array $defaults ) : Field_Callback Add expression field.
addField ( string $name, array $defaults = [] ) : Field Adds new field into model.
addFields ( array $fields = [], array $defaults = [] ) Adds multiple fields into model.
addRef ( string $link, array $callback ) : object Add generic relation. Provide your own call-back that will return the model.
allFields ( ) Sets that we should select all available fields.
asModel ( string $class, array $options = [] ) : Model This will cast Model into another class without loosing state of your active record.
atomic ( callable $f ) : mixed Atomic executes operations within one begin/end transaction, so if the code inside callback will fail, then all of the transaction will be also rolled back.
delete ( mixed $id = null ) Delete record with a specified id. If no ID is specified then current record is deleted.
duplicate ( mixed | null $new_id = null ) Keeps the model data, but wipes out the ID so when you save it next time, it ends up as a new record in the database.
each ( string | callable $method ) Executes specified method or callback for each record in DataSet.
export ( array | null $fields = null ) : array Export DataSet as array of hashes.
get ( mixed $field = null ) : mixed Returns field value.
getIterator ( ) : mixed Returns iterator (yield values).
getRef ( string $link ) : Field Return reference field.
getRefs ( ) : array Returns all reference fields.
hasMany ( string $link, array $defaults = [] ) : Reference_Many Add hasMany field.
hasOne ( string $link, array $defaults = [] ) : Reference_One Add hasOne field.
hasRef ( string $link ) : Field | boolean Return reference field or false if reference field does not exist.
import ( $rows ) Even more faster method to add data, does not modify your current record and will not return anything.
init ( ) Extend this method to define fields of your choice.
insert ( array $row ) : mixed Faster method to add data, that does not modify active record.
isDirty ( $fields = [] ) : boolean Will return true if any of the specified fields are dirty.
join ( string $foreign_table, array $defaults = [] ) : Join Creates an objects that describes relationship between multiple tables (or collections).
leftJoin ( string $foreign_table, array $defaults = [] ) : Join Left Join support.
load ( mixed $id ) Load model.
loadAny ( ) Load any record.
loadBy ( mixed $field, mixed $value ) Load record by condition.
loaded ( ) : boolean Is model loaded?
newInstance ( string $class = null, array $options = [] ) : Model Create new model from the same base class as $this.
offsetExists ( string $name ) : boolean Do field exist?
offsetGet ( string $name ) : mixed Returns field value.
offsetSet ( string $name, mixed $val ) Set field value.
offsetUnset ( string $name ) Redo field value.
onlyFields ( array $fields = [] ) Sets which fields we will select.
rawIterator ( ) : Iterator Returns iterator.
ref ( string $link, array $defaults = [] ) : Model Traverse to related model.
refLink ( string $link, array $defaults = [] ) : Model Returns model that can be used for generating sub-query actions.
refModel ( string $link, array $defaults = [] ) : Model Return related model.
reload ( ) Reload model by taking its current ID.
save ( $data = [] )
saveAndUnload ( array $data = [] ) Store the data into database, but will never attempt to reload the data. Additionally any data will be unloaded.
saveAs ( string $class, array $options = [] ) : Model Saves the current record by using a different model class. This is similar to:.
set ( string | array $field, mixed $value = null ) Set field value.
setDefaults ( array $defaults ) Set default properties of model.
setLimit ( integer $count, integer | null $offset = null ) Set limit of DataSet.
setOrder ( mixed $field, boolean | null $desc = null ) Set order for model records. Multiple calls.
tryLoad ( mixed $id ) Try to load record.
tryLoadAny ( ) Try to load any record.
tryLoadBy ( mixed $field, mixed $value ) Try to load record by condition.
unload ( ) Unload model.
withID ( mixed $id ) Shortcut for using addCondition(id_field, $id).
withPersistence ( Persistence $persistence, mixed $id = null, string $class = null ) Create new model from the same base class as $this. If you omit $id,then when saving a new record will be created with default ID.

Защищенные методы

Метод Описание
_hasReference ( string $c, string $link, array $defaults = [] ) : object Private method.
_rawInsert ( Model $m, array $row ) This is a temporary method to avoid code duplication, but insert / import should be implemented differently.

Приватные методы

Метод Описание
normalizeFieldName ( mixed $field ) : string Normalize field name.

Описание методов

__clone() публичный Метод

public __clone ( )

__construct() публичный Метод

$m = $db->add(new Model()); or $m = new Model($db); The second use actually calls add() but is preferred usage because: - it's shorter - type hinting will work;
public __construct ( Persistence | array $persistence = null, array $defaults = [] )
$persistence Persistence | array
$defaults array

__debugInfo() публичный Метод

Returns array with useful debug info for var_dump.
public __debugInfo ( ) : array
Результат array

_hasReference() защищенный Метод

Private method.
protected _hasReference ( string $c, string $link, array $defaults = [] ) : object
$c string Class name
$link string Link
$defaults array Properties which we will pass to Reference object constructor
Результат object

_init() публичный Метод

public _init ( )

_rawInsert() защищенный Метод

This is a temporary method to avoid code duplication, but insert / import should be implemented differently.
protected _rawInsert ( Model $m, array $row )
$m Model
$row array

_unset() публичный Метод

Remove current field value and use default.
public _unset ( string | array $name )
$name string | array

action() публичный Метод

Execute action.
public action ( string $mode, array $args = [] ) : atk4\dsql\Query
$mode string
$args array
Результат atk4\dsql\Query

addCondition() публичный Метод

This is the most basic for defining condition: ->addCondition('my_field', $value); This condition will work across all persistence drivers universally. In some cases a more complex logic can be used: ->addCondition('my_field', '>', $value); ->addCondition('my_field', '!=', $value); ->addCondition('my_field', 'in', [$value1, $value2]); Second argument could be '=', '>', '<', '>=', '<=', '!=' or 'in'. Those conditions are still supported by most of persistence drivers. There are also vendor-specific expression support: ->addCondition('my_field', $expr); ->addCondition($expr); To use those, you should consult with documentation of your persistence driver.
public addCondition ( mixed $field, mixed $operator = null, mixed $value = null )
$field mixed
$operator mixed
$value mixed

addExpression() публичный Метод

Add expression field.
public addExpression ( string $name, array $defaults ) : Field_Callback
$name string
$defaults array
Результат Field_Callback

addField() публичный Метод

Adds new field into model.
public addField ( string $name, array $defaults = [] ) : Field
$name string
$defaults array
Результат Field

addFields() публичный Метод

Adds multiple fields into model.
public addFields ( array $fields = [], array $defaults = [] )
$fields array
$defaults array

addRef() публичный Метод

Add generic relation. Provide your own call-back that will return the model.
public addRef ( string $link, array $callback ) : object
$link string Link
$callback array Callback
Результат object

allFields() публичный Метод

Sets that we should select all available fields.
public allFields ( )

asModel() публичный Метод

This will cast Model into another class without loosing state of your active record.
public asModel ( string $class, array $options = [] ) : Model
$class string
$options array
Результат Model

atomic() публичный Метод

Atomic executes operations within one begin/end transaction, so if the code inside callback will fail, then all of the transaction will be also rolled back.
public atomic ( callable $f ) : mixed
$f callable
Результат mixed

delete() публичный Метод

Delete record with a specified id. If no ID is specified then current record is deleted.
public delete ( mixed $id = null )
$id mixed

duplicate() публичный Метод

Keeps the model data, but wipes out the ID so when you save it next time, it ends up as a new record in the database.
public duplicate ( mixed | null $new_id = null )
$new_id mixed | null

each() публичный Метод

Executes specified method or callback for each record in DataSet.
public each ( string | callable $method )
$method string | callable

export() публичный Метод

Export DataSet as array of hashes.
public export ( array | null $fields = null ) : array
$fields array | null
Результат array

get() публичный Метод

If no field is passed, then returns array of all field values.
public get ( mixed $field = null ) : mixed
$field mixed
Результат mixed

getIterator() публичный Метод

Returns iterator (yield values).
public getIterator ( ) : mixed
Результат mixed

getRef() публичный Метод

Return reference field.
public getRef ( string $link ) : Field
$link string
Результат Field

getRefs() публичный Метод

Returns all reference fields.
public getRefs ( ) : array
Результат array

hasMany() публичный Метод

Add hasMany field.
public hasMany ( string $link, array $defaults = [] ) : Reference_Many
$link string
$defaults array
Результат Reference_Many

hasOne() публичный Метод

Add hasOne field.
public hasOne ( string $link, array $defaults = [] ) : Reference_One
$link string
$defaults array
Результат Reference_One

hasRef() публичный Метод

Return reference field or false if reference field does not exist.
public hasRef ( string $link ) : Field | boolean
$link string
Результат Field | boolean

import() публичный Метод

Will be further optimized in the future.
public import ( $rows )

init() публичный Метод

Extend this method to define fields of your choice.
public init ( )

insert() публичный Метод

Will be further optimized in the future.
public insert ( array $row ) : mixed
$row array
Результат mixed

isDirty() публичный Метод

Will return true if any of the specified fields are dirty.
public isDirty ( $fields = [] ) : boolean
Результат boolean

join() публичный Метод

When object is loaded, then instead of pulling all the data from a single table, join will also query $foreign_table in order to find additional fields. When inserting the record will be also added inside $foreign_table and relationship will be maintained.
public join ( string $foreign_table, array $defaults = [] ) : Join
$foreign_table string
$defaults array
Результат Join

leftJoin() публичный Метод

Left Join support.
См. также: join()
public leftJoin ( string $foreign_table, array $defaults = [] ) : Join
$foreign_table string
$defaults array
Результат Join

load() публичный Метод

Load model.
public load ( mixed $id )
$id mixed

loadAny() публичный Метод

Load any record.
public loadAny ( )

loadBy() публичный Метод

Load record by condition.
public loadBy ( mixed $field, mixed $value )
$field mixed
$value mixed

loaded() публичный Метод

Is model loaded?
public loaded ( ) : boolean
Результат boolean

newInstance() публичный Метод

Create new model from the same base class as $this.
public newInstance ( string $class = null, array $options = [] ) : Model
$class string
$options array
Результат Model

offsetExists() публичный Метод

Do field exist?
public offsetExists ( string $name ) : boolean
$name string
Результат boolean

offsetGet() публичный Метод

Returns field value.
public offsetGet ( string $name ) : mixed
$name string
Результат mixed

offsetSet() публичный Метод

Set field value.
public offsetSet ( string $name, mixed $val )
$name string
$val mixed

offsetUnset() публичный Метод

Redo field value.
public offsetUnset ( string $name )
$name string

onlyFields() публичный Метод

Sets which fields we will select.
public onlyFields ( array $fields = [] )
$fields array

rawIterator() публичный Метод

Returns iterator.
public rawIterator ( ) : Iterator
Результат Iterator

ref() публичный Метод

Traverse to related model.
public ref ( string $link, array $defaults = [] ) : Model
$link string
$defaults array
Результат Model

refModel() публичный Метод

Return related model.
public refModel ( string $link, array $defaults = [] ) : Model
$link string
$defaults array
Результат Model

reload() публичный Метод

Reload model by taking its current ID.
public reload ( )

save() публичный Метод

public save ( $data = [] )

saveAndUnload() публичный Метод

Use this instead of save() if you want to squezee a little more performance out.
public saveAndUnload ( array $data = [] )
$data array

saveAs() публичный Метод

$m2 = $m->newInstance($class); $m2->load($m->id); $m2->set($m->get()); $m2->save(); but will assume that both models are compatible, therefore will not perform any loading.
public saveAs ( string $class, array $options = [] ) : Model
$class string
$options array
Результат Model

set() публичный Метод

Set field value.
public set ( string | array $field, mixed $value = null )
$field string | array
$value mixed

setDefaults() публичный Метод

Set default properties of model.
public setDefaults ( array $defaults )
$defaults array

setLimit() публичный Метод

Set limit of DataSet.
public setLimit ( integer $count, integer | null $offset = null )
$count integer
$offset integer | null

setOrder() публичный Метод

Set order for model records. Multiple calls.
public setOrder ( mixed $field, boolean | null $desc = null )
$field mixed
$desc boolean | null

tryLoad() публичный Метод

Will not throw exception if record doesn't exist.
public tryLoad ( mixed $id )
$id mixed

tryLoadAny() публичный Метод

Will not throw exception if record doesn't exist.
public tryLoadAny ( )

tryLoadBy() публичный Метод

Will not throw exception if record doesn't exist.
public tryLoadBy ( mixed $field, mixed $value )
$field mixed
$value mixed

unload() публичный Метод

Unload model.
public unload ( )

withID() публичный Метод

Shortcut for using addCondition(id_field, $id).
public withID ( mixed $id )
$id mixed

withPersistence() публичный Метод

If you specify $id then it will be used to save/update your record. If set $id to true then model will assume that there is already record like that in the destination persistence. If you wish to fully copy the data from one model to another you should use: $m->withPersintence($p2, false)->set($m)->save(); See https://github.com/atk4/data/issues/111 for use-case examples.
public withPersistence ( Persistence $persistence, mixed $id = null, string $class = null )
$persistence Persistence
$id mixed
$class string

Описание свойств

$_default_class_addExpression публичное свойство

The class used by addField() method.
public string $_default_class_addExpression
Результат string

$_default_class_addField публичное свойство

The class used by addField() method.
public string $_default_class_addField
Результат string

$_default_class_hasMany публичное свойство

The class used by hasMany() method.
public string $_default_class_hasMany
Результат string

$_default_class_hasOne публичное свойство

The class used by hasOne() method.
public string $_default_class_hasOne
Результат string

$_default_class_join публичное свойство

The class used by join() method.
public string $_default_class_join
Результат string

$_dirty_after_reload публичное свойство

Save record.
public $_dirty_after_reload

$conditions публичное свойство

Conditions list several conditions that must be met by all the records in the associated DataSet. Conditions are stored as elements of array of 1 to 3. Use addCondition() to add new conditions.
public array $conditions
Результат array

$data публичное свойство

Avoid accessing $data directly, use set() / get() instead.
public array $data
Результат array

$dirty публичное свойство

If the value you set equal to the original value, then the key in this array will be removed. The $dirty data will be reset after you save() the data but it is still available to all before/after save handlers.
public array $dirty
Результат array

$id публичное свойство

Contains ID of the current record. If the value is null then the record is considered to be new.
public mixed $id
Результат mixed

$id_field публичное свойство

While in most cases your id field will be called 'id', sometimes you would want to use a different one or maybe don't create field at all.
public string $id_field
Результат string

$limit публичное свойство

Array of limit set.
public array $limit
Результат array

$load_normalization публичное свойство

When set to true, loading model from database will also perform value normalization. Use this if you think that persistence may contain badly formatted data that may impact your business logic.
public bool $load_normalization
Результат boolean

$only_fields публичное свойство

When you have used onlyFields() before loading the data for this model, then only that set of fields will be available. Attempt to access any other field will result in exception. This is to ensure that you do not accidentally access field that you have explicitly excluded. The default behavior is to return NULL and allow you to set new fields even if addField() was not used to set the field.
public false|array $only_fields
Результат false | array

$order публичное свойство

Array of set order by.
public array $order
Результат array

$persistence публичное свойство

Persistence driver inherited from atk4\data\Persistence.
public Persistence,atk4\data $persistence
Результат Persistence

$persistence_data публичное свойство

Persistence store some custom information in here that may be useful for them. The key is the name of persistence driver.
public array $persistence_data
Результат array

$reload_after_save публичное свойство

This is to ensure that any SQL-based calculation are executed and updated correctly after you have performed any modifications to the fields. You can set this property to "true" or "false" if you want to explicitly enable or disable reloading.
public bool|null $reload_after_save
Результат boolean | null

$strict_field_check защищенное свойство

In some situations you want to set field value and then declare it later, then set $strict_field_check = false, but it's not recommended.
protected bool $strict_field_check
Результат boolean

$strict_types публичное свойство

When set to true, all the field types will be enforced and normalized when setting.
public bool $strict_types
Результат boolean

$table публичное свойство

You can define this field as associative array where "key" is used as the name of persistence driver. Here is example for mysql and default: $table = ['user', 'mysql'=>'tbl_user'];
public string|array $table
Результат string | array

$title_field публичное свойство

$model->importRows(['Bananas','Oranges']); // 2 records imported
public string $title_field
Результат string