-
Notifications
You must be signed in to change notification settings - Fork 34
classes_essentials_model_model.class
This is base class for data objects. It provides all the stuff to handle DB access really simple following the ActiveRecord paradigm. Implements Iterator, Countable and ArrayAccess for ease of use in for and foreach loops. Also has methods like all(), like() and so on to access your data the really easy way:
$some_does = MyModelClass::Make()->orAll()->like('firstname','%john%')->equal('lastname','doe');
foreach( $some_does as $sd ) echo $sd;
Implements: Iterator Countable ArrayAccess
Subclasses: CommonModel, OAuthStorageModel, RequestLogEntry, WdfTaskModel
Ensures a valid select query.
Similar to Model::noop but will not add the 1=1 condition.
Definition: public function all()
Returns: Model clone $this
Marks that from now on all following conditions will be AND combined.
Note that this is default behaviour!
$q1 = MyModel::Make()->andAll()->eq('id',1)->gt('sort',2);
// as andAll() is default that is the same like this
$q2 = MyModel::Make()->eq('id',1)->gt('sort',2); Definition: public function andAll()
Returns: Model clone $this
Marks that the next X conditions will be AND combined.
$q1 = MyModel::Make()->orAll()->eq('id',1)->andX(2)->gt('sort',2)->lt('sort',10);
// SELECT FROM my_model WHERE id=1 OR (sort>2 AND sort<10) Definition: public function andX($count)
Returns: Model clone $this
Parameters:
-
int $countHow many following calls shall be AND-combined
Returns all field values a array.
Definition: public function AsArray($filter)
Returns: array Associative array of fieldname=>value pairs
Parameters:
-
mixed $filterList of column names to return (each: if value present)
Returns an array that may be used in other DB statements. The returned array will be associative, the column names as keys will be prepended with ':'. Sample usage:
$model = new SomeModel();
$sql = "SELECT * FROM some_table WHERE id=:id";
DataSource::Get()->ExecuteSql($sql,$model->AsDbArgs('id')); Definition: public function AsDbArgs($names)
Returns: array Associative array of fieldname=>value pairs
Parameters:
-
mixed $namesList of column names to return (each: if value present)
Returns a JSON representation of this object.
If fact it is just a shortcut to json_encode($this->AsArray($filter)).
Definition: public function AsJson($filter)
Returns: string
Parameters:
-
mixed $filterList of column names to return (each: if value present)
Check if a fields value is binary equal to another value.
Definition: public function binary($property, $value)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
mixed $valueValue to check against
Typecasts a Model (sub-)class to another type.
$entry = $ds->Query('my_table')->eq('id',1)->current(); // $entry is instance of CommonModel
$entry = MyTableModel::CastFrom($entry); // now it is type of MyTableModel Definition: public static function CastFrom($model, $allFields=false, $className=false)
Returns: static The typed object
Parameters:
-
Model $modelObject of (sub-)type Model -
bool $allFieldsIf true, all data is taken to the result, not only that one that are present in the columns of the type -
bool|string $classNameOptional classname to allow anonymous calls like Model::MakeFromData
SHORTCUT Model::like($property,"%$value%")
Returns the amount of results in the current query.
Definition: public function count()
Returns: int Amount of results
Derivered classes can override this to create their table.
Definition: protected function CreateTable()
Returns: void
IMPLEMENTS Iterator::current
INTERNAL Returns the name of the assigned DataSource (the alias)
Deletes this model from the database.
Definition: public function Delete()
Returns: bool true or false
Ends a condition sub-tree.
Definition: public function end()
Returns: static
SHORTCUT Model::like($property,"%$value")
Static tool method to ensure $value is of type DateTimeEx.
Definition: public static function EnsureDateTime($value, $convert_now_to_value=false)
Returns: mixed DateTimeEx value or 'now()' if $convert_now_to_value is fale and value is 'now()'
Parameters:
-
mixed $valueSome value representing a datetime -
bool $convert_now_to_valueif true will check if$value=='now()'and if so returnnew DateTimeExinstead of'now()'
Enumerates all values from a column of the current result.
$emails = MyModel::Make()->lt('id',1000)->enumerate('email',true); Definition: public function enumerate($property_or_fieldname, $distinct=true, $key_column_name=false)
Returns: array Array of values
Parameters:
-
string $property_or_fieldnameProperty-/Fieldname -
bool $distinctIf true will array_unique the results. -
string $key_column_nameIf given uses this column as key for an associative resulting array
SHORTCUT Model::equal($property,$value,$value_is_sql)
Check if a field has a value.
Definition: public function equal($property, $value, $value_is_sql=false)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
mixed $valueValue to check for -
bool $value_is_sqlif true, $value is treaded as SQL keyword/function/... and will remain unescaped (sample: now())
Returns column values.
Definition: public function FieldValues($args)
Returns: array plain array of values
Parameters:
-
mixed $argsColumn names
Selects Models from the database with a partial SQL statement.
Definition: public function Find($where, $prms)
Returns: array Array of Model datasets
Parameters:
-
string $whereWHERE-part of the SQL statement. -
array $prmsArguments used in $where
Creates a full qualified fieldname. That is ```tablename`.field_name``
Definition: public function FullQualifiedFieldName($name)
Returns: string FQ fieldname
Parameters:
-
string $nameName to FQ
Returns an array of changes. The result is an array with column names as keys and each element an array of the old an the new value.
Definition: public function GetChanges()
Returns: array Array containing all changes
Returns a list of column names. If $changed_only is true will only return names of fields which values have been changed compared to the saved values. *
Definition: public function GetColumnNames($changed_only=false)
Returns: array A list of column names
Parameters:
-
bool $changed_onlyReturn only changed columns names
SHORTCUT ResultSet::GetPagingInfo
Returns the names of all primary columns.
Definition: public function GetPrimaryColumns()
Returns: array List of all columns that belong to the primary key
Derivered classes must implement this and return the table name they are stored in.
Definition: public abstract function GetTableName()
Returns: string Table name
Returns the TableSchema of this Model.
Definition: public function GetTableSchema()
Returns: TableSchema
Check if a fields value is greater than something.
Definition: public function greaterThan($property, $value, $value_is_sql=false)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
mixed $valueValue to check against -
bool $value_is_sqlif true, $value is treaded as SQL keyword/function/... and will fremain unescaped (sample: now())
Check if a fields value is greater than or equal to something.
Definition: public function greaterThanOrEqualTo($property, $value)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
mixed $valueValue to check against
Adds a groupBy statement to the query.
Definition: public function groupBy($property)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname to group by
SHORTCUT Model::greaterThan($property, $value)
SHORTCUT Model::greaterThanOrEqualTo($property, $value)
Checks if a column has changed.
Definition: public function HasChanged($col)
Returns: bool true if changed, else false
Parameters:
-
string $colName of the column to check
Checks if this Model has a column $name.
Definition: public function HasColumn($name)
Returns: bool true or false
Parameters:
-
string $nameColumn name to check for
Checks if there's a value set for the given column.
Definition: public function HasValue($name)
Returns: bool
Parameters:
-
string $nameColumn name
Adds a HAVING statement.
Definition: public function having($defaultOperator)
Returns: Model clone $this
Parameters:
-
string $defaultOperator'AND' or 'OR'
Checks if a fields value is one of the $values.
Definition: public function in($property, $values)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
array $valuesArray of values to check against
Filters by "the given date is between start & end".
Definition: public function isDateInRange($startfieldname, $endfieldname, $date=false)
Returns: Model $this
Parameters:
-
string $startfieldnameName of the column containing the start date(-time) -
string $endfieldnameName of the column containing the end date(-time) -
mixed $dateThe date value to be chacked against
SHORTCUT Model::newerThan($property,0,'second') Filters by date values in the future
Checks if a fields value is NULL.
Definition: public function isNull($property)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname
SHORTCUT Model::olderThan($property,0,'second')
Returns true is this is a query, false if this represents a datatset
Definition: public function IsQuery()
Returns: bool true or false
Returns true is this is a dataset, false if this represents a query
Definition: public function IsRow()
Returns: bool true or false
Join two database tables.
Definition: public function join($direction, $model)
Returns: Model clone $this
Parameters:
-
string $directionE.g. 'LEFT', 'RIGHT' or 'FULL'. Also 'LEFT OUTER'. -
Model $modelAn instance of a Model subclass.
IMPLEMENTS Iterator::key
Check if a fields value is LIKE another value. See http://www.w3schools.com/sql/sql_like.asp
Definition: public function like($property, $value, $flipped=false)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
mixed $valueValue to check against -
bool $flippedIf true, expects the roles of $property and $value switched
SHORTCUT Model::page(0,$limit);
Loads a Model using SQL. All field values will be loaded from DB.
Definition: public function Load($where, $arguments=false)
Returns: bool true if dataset was found, else false
Parameters:
-
string $whereWHERE-part of the SQL statement. -
array|mixed $argumentsArguments used in $where
SHORTCUT ResultSet::LogDebug
Check if a fields value is lower than something.
Definition: public function lowerThan($property, $value)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
mixed $valueValue to check against
Check if a fields value is lower than or equal to something.
Definition: public function lowerThanOrEqualTo($property, $value)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
mixed $valueValue to check against
SHORTCUT Model::lowerThan($property, $value)
SHORTCUT Model::lowerThanOrEqualTo($property,$value)
Static creator method for easy Model instaciation and instant method chaining
$new_datasets = MyModelClass::Make()->youngerThan('created',1,'month'); There's also a shortcut syntax to load a dataset automatically, but this will only work if the tables primary key constist of only one column:
$loaded = MyModelClass::Make(null,2); Definition: public static function Make($datasource=null, $pk_value=false)
Returns: static Returns the created model or null, if nothing can be found for a specified $pk_value
Parameters:
-
DataSource $datasourceDataSource to bind to, defaults to Model::$DefaultDatasource -
mixed $pk_valuePrimary key value
Creates a typed Model object from array-based data. You may optionally add a datasource.
function make_new_contact(array $data)
{
ContactModel::MakeFromData($data)->Save();
} Definition: public static function MakeFromData($data, $datasource=null, $allFields=false, $className=false)
Returns: static The newly created typed Model
Parameters:
-
array $dataAssociative array with data -
DataSource $datasourceOptional datasource to assign to the created Model -
bool $allFieldsIf true, all data is taken to the result, not only that one that are present in the columns of the type -
bool $classNameOptional classname to allow anonymous calls like Model::MakeFromData
SHORTCUT Model::notEqual($property,$value)
Check if a fields value is binary NOT equal to another value.
Definition: public function neqBinary($property, $value)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
mixed $valueValue to check against
Condition: column $property must be datetime and it's value newer than given interval See DateTimeEx::youngerThan
Definition: public function newerThan($property, $value, $interval)
Returns: Model clone $this
Parameters:
-
string $propertyProperpy-/Fieldname -
int $valueOffset value -
string $intervalUnit
IMPLEMENTS Iterator::next
This is just a 'no operation' method.
You may use to ensure there's a valid query built by adding 1=1 to the conditions
$q = MyModel::Make()->noop();
$m1 = $q->eq('id',1)->current();
$m2 = $q->eq('id',2)->current(); Definition: public function noop()
Returns: Model clone $this
Check if a field has NOT a BINARY value.
Definition: public function notBinary($property, $value)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
mixed $valueValue to check for
Check if a field has NOT a value.
Definition: public function notEqual($property, $value)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
mixed $valueValue to check for
Checks if a fields value is NOT one of the $values.
Definition: public function notIn($property, $values)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
array $valuesArray of values to check against
Checks if a fields value is NOT NULL.
Definition: public function notNull($property)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname
IMPLEMENTS ArrayAccess::offsetExists
IMPLEMENTS ArrayAccess::offsetGet
IMPLEMENTS ArrayAccess::offsetSet
IMPLEMENTS ArrayAccess::offsetUnset
Condition: column $property must be datetime and it's value older than given interval See DateTimeEx::olderThan
Definition: public function olderThan($property, $value, $interval)
Returns: Model clone $this
Parameters:
-
string $propertyProperpy-/Fieldname -
int $valueOffset value -
string $intervalUnit
Marks that from now on all following conditions will be OR combined.
$q = MyModel::Make()->orAll()->eq('id',1)->eq('id',2); Definition: public function orAll()
Returns: Model clone $this
Adds a orderBy statement to the query.
Definition: public function orderBy($property, $direction, $checkfieldname=true)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname to order by -
string $direction'ASC' or 'DESC' -
bool $checkfieldnameCheck the fieldname or not (true|false)
Marks that the next X conditions will be OR combined.
$q1 = MyModel::Make()->orX(2)->eq('id',1)->andX(2)->gt('sort',2)->lt('sort',10);
// SELECT FROM my_model WHERE id=1 OR (sort>2 AND sort<10) Definition: public function orX($count)
Returns: Model clone $this
Parameters:
-
int $countHow many following calls shall be OR-combined
SHORTCUT Model::olderThan($property, $value, $interval)
Adds paging to the query.
Definition: public function page($offset, $items)
Returns: Model clone $this
Parameters:
-
int $offsetZero-based offset -
int $itemsMaximum items to return
Calls a callback function for each result dataset. Callback function will receive each row as Model object and must return the (eventually changed) Model object. Note that this method will not clone the result, but return the object itself!
Definition: public function process($callback)
Returns: Model Returns $this
Parameters:
-
mixed $callbackAnonymous callback function
Queries the database for Models but using an SQL statement. Use this if you do not like the QueryBuilder or if you have really complicated queries.
Definition: public static function Query($sql, $args, $datasource=null)
Returns: static The result set
Parameters:
-
string $sqlStatement -
array $argsArguments -
DataSource $datasourceUse this datasource
Returns an array containing all results. In fact you may use the Model itself in foreach loops or stuff, but sometimes it is better to get a plain array. For example if you need to test with is_array.
Definition: public function results()
Returns: array Array of results (may be empty)
IMPLEMENTS Iterator::rewind
Check if a fields value is RLIKE another value. MySQL specific: see http://dev.mysql.com/doc/refman/5.1/en/regexp.html
Definition: public function rlike($property, $value, $flipped=false)
Returns: Model clone $this
Parameters:
-
string $propertyProperty-/Fieldname -
mixed $valueValue to check against -
bool $flippedIf true switches the roles of $property and $value
DEPRECATED (2022/07) This uses a non existant function, so atm does nothing Uses <system_sanitize_parameters> to sanitze all field values.
Saves this model to the database. New datasets will be inserted, loaded ones will be updated automatically. If $columns_to_update is given only those columns will be stored. This may be useful to avoid DB conflicts in multithread scenarios.
Definition: public function Save($columns_to_update=false, $changed=null)
Returns: bool In fact always true, WdfDbException will be thrown in error case
Parameters:
-
array $columns_to_update(Optional) If given only these fields will be updated. If not Model tries to detect changed columns automatically. -
array $changed(Optional) Save will fill this array with all changes in the form ['name'=>['old','new'],...]
Returns a single value from the first result object in the query.
$name = $ds->Query('sometable')->eq('id')->scalar('name'); Definition: public function scalar($property, $default=null)
Returns: mixed The value of $default
Parameters:
-
array|string $propertyProperty name -
mixed $defaultDefault if nothing was found
SHORTCUT Model::Make($datasource)
Like Model::orderBy but adds 'ORDER BY rand()'.
Definition: public function shuffle()
Returns: Model clone $this
Adds a raw SQL part to the statement.
Definition: public function sql($sql_statement_part, $args)
Returns: Model clone $this
Parameters:
-
string $sql_statement_partThe raw SQL code -
array $argsThe arguments of the raw SQL query part
SHORTCUT Model::like($property,"$value%")
Tries to find a model by its table name. ATM this is crap. We'll need some kind of database schema description to be able to map models to tables and on the same time ensure table structure. That way we will get real Code-First ORM.
Definition: public static function TryGetClassFromTablename($tablename, $ds=null)
Returns: string The Model classname if found, an empty string otherwise.
Parameters:
-
string $tablenameThe name of the table -
DataSource $dsOptional datasource to use.
INTERNAL Wrapper around private method to allow overriding without breaking internal functionality
INTERNAL Wrapper around private method to allow overriding without breaking internal functionality
Passes all given arguments as column names to the Save method.
Use it like this: $model->Update('age','last_action');
when you want to ensure that only these columns are written.
See Model::Save() for more information.
Definition: public function Update($args)
Returns: Model clone $this
Parameters:
-
mixed $argsThe columns names to save
IMPLEMENTS Iterator::valid
SHORTCUT Model::newerThan($property, $value, $interval)
SHORTCUT Model::newerThan($property, $value, $interval)
Definition: protected function __log_dynamic_property_access($name)
Returns: NOT DOCUMENTED
Parameters:
-
$nameNOT DOCUMENTED