PHP Class atk4\data\Model

Inheritance: 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
Mostra file Open project: atk4/data Class Usage Examples

Public Properties

Property Type Description
$_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 Properties

Property Type Description
$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.

Public Methods

Method Description
__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.

Protected Methods

Method Description
_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.

Private Methods

Method Description
normalizeFieldName ( mixed $field ) : string Normalize field name.

Method Details

__clone() public method

public __clone ( )

__construct() public method

$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() public method

Returns array with useful debug info for var_dump.
public __debugInfo ( ) : array
return array

_hasReference() protected method

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
return object

_init() public method

public _init ( )

_rawInsert() protected method

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() public method

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

action() public method

Execute action.
public action ( string $mode, array $args = [] ) : atk4\dsql\Query
$mode string
$args array
return atk4\dsql\Query

addCondition() public method

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() public method

Add expression field.
public addExpression ( string $name, array $defaults ) : Field_Callback
$name string
$defaults array
return Field_Callback

addField() public method

Adds new field into model.
public addField ( string $name, array $defaults = [] ) : Field
$name string
$defaults array
return Field

addFields() public method

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

addRef() public method

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
return object

allFields() public method

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

asModel() public method

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
return Model

atomic() public method

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
return mixed

delete() public method

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

duplicate() public method

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() public method

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

export() public method

Export DataSet as array of hashes.
public export ( array | null $fields = null ) : array
$fields array | null
return array

get() public method

If no field is passed, then returns array of all field values.
public get ( mixed $field = null ) : mixed
$field mixed
return mixed

getIterator() public method

Returns iterator (yield values).
public getIterator ( ) : mixed
return mixed

getRef() public method

Return reference field.
public getRef ( string $link ) : Field
$link string
return Field

getRefs() public method

Returns all reference fields.
public getRefs ( ) : array
return array

hasMany() public method

Add hasMany field.
public hasMany ( string $link, array $defaults = [] ) : Reference_Many
$link string
$defaults array
return Reference_Many

hasOne() public method

Add hasOne field.
public hasOne ( string $link, array $defaults = [] ) : Reference_One
$link string
$defaults array
return Reference_One

hasRef() public method

Return reference field or false if reference field does not exist.
public hasRef ( string $link ) : Field | boolean
$link string
return Field | boolean

import() public method

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

init() public method

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

insert() public method

Will be further optimized in the future.
public insert ( array $row ) : mixed
$row array
return mixed

isDirty() public method

Will return true if any of the specified fields are dirty.
public isDirty ( $fields = [] ) : boolean
return boolean

join() public method

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
return Join

leftJoin() public method

Left Join support.
See also: join()
public leftJoin ( string $foreign_table, array $defaults = [] ) : Join
$foreign_table string
$defaults array
return Join

load() public method

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

loadAny() public method

Load any record.
public loadAny ( )

loadBy() public method

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

loaded() public method

Is model loaded?
public loaded ( ) : boolean
return boolean

newInstance() public method

Create new model from the same base class as $this.
public newInstance ( string $class = null, array $options = [] ) : Model
$class string
$options array
return Model

offsetExists() public method

Do field exist?
public offsetExists ( string $name ) : boolean
$name string
return boolean

offsetGet() public method

Returns field value.
public offsetGet ( string $name ) : mixed
$name string
return mixed

offsetSet() public method

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

offsetUnset() public method

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

onlyFields() public method

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

rawIterator() public method

Returns iterator.
public rawIterator ( ) : Iterator
return Iterator

ref() public method

Traverse to related model.
public ref ( string $link, array $defaults = [] ) : Model
$link string
$defaults array
return Model

refModel() public method

Return related model.
public refModel ( string $link, array $defaults = [] ) : Model
$link string
$defaults array
return Model

reload() public method

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

save() public method

public save ( $data = [] )

saveAndUnload() public method

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

saveAs() public method

$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
return Model

set() public method

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

setDefaults() public method

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

setLimit() public method

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

setOrder() public method

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

tryLoad() public method

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

tryLoadAny() public method

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

tryLoadBy() public method

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

unload() public method

Unload model.
public unload ( )

withID() public method

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

withPersistence() public method

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

Property Details

$_default_class_addExpression public_oe property

The class used by addField() method.
public string $_default_class_addExpression
return string

$_default_class_addField public_oe property

The class used by addField() method.
public string $_default_class_addField
return string

$_default_class_hasMany public_oe property

The class used by hasMany() method.
public string $_default_class_hasMany
return string

$_default_class_hasOne public_oe property

The class used by hasOne() method.
public string $_default_class_hasOne
return string

$_default_class_join public_oe property

The class used by join() method.
public string $_default_class_join
return string

$_dirty_after_reload public_oe property

Save record.
public $_dirty_after_reload

$conditions public_oe property

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
return array

$data public_oe property

Avoid accessing $data directly, use set() / get() instead.
public array $data
return array

$dirty public_oe property

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
return array

$id public_oe property

Contains ID of the current record. If the value is null then the record is considered to be new.
public mixed $id
return mixed

$id_field public_oe property

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
return string

$limit public_oe property

Array of limit set.
public array $limit
return array

$load_normalization public_oe property

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
return boolean

$only_fields public_oe property

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
return false | array

$order public_oe property

Array of set order by.
public array $order
return array

$persistence public_oe property

Persistence driver inherited from atk4\data\Persistence.
public Persistence,atk4\data $persistence
return Persistence

$persistence_data public_oe property

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
return array

$reload_after_save public_oe property

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
return boolean | null

$strict_field_check protected_oe property

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
return boolean

$strict_types public_oe property

When set to true, all the field types will be enforced and normalized when setting.
public bool $strict_types
return boolean

$table public_oe property

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
return string | array

$title_field public_oe property

$model->importRows(['Bananas','Oranges']); // 2 records imported
public string $title_field
return string