Skip to content

classes_essentials_model_model.class

Daniel Spors edited this page Mar 11, 2024 · 4 revisions

Classes in file essentials/model/model.class.php

abstract class Model

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

all

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

andAll

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

andX

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 $count How many following calls shall be AND-combined

AsArray

Returns all field values a array.

Definition: public function AsArray($filter)

Returns: array Associative array of fieldname=>value pairs

Parameters:

  • mixed $filter List of column names to return (each: if value present)

AsDbArgs

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 $names List of column names to return (each: if value present)

AsJson

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 $filter List of column names to return (each: if value present)

binary

Check if a fields value is binary equal to another value.

Definition: public function binary($property, $value)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

  • mixed $value Value to check against

CastFrom

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 $model Object of (sub-)type Model

  • bool $allFields If true, all data is taken to the result, not only that one that are present in the columns of the type

  • bool|string $className Optional classname to allow anonymous calls like Model::MakeFromData

contains

SHORTCUT Model::like($property,"%$value%")

count

Returns the amount of results in the current query.

Definition: public function count()

Returns: int Amount of results

CreateTable

Derivered classes can override this to create their table.

Definition: protected function CreateTable()

Returns: void

current

IMPLEMENTS Iterator::current

DataSourceName

INTERNAL Returns the name of the assigned DataSource (the alias)

Delete

Deletes this model from the database.

Definition: public function Delete()

Returns: bool true or false

end

Ends a condition sub-tree.

Definition: public function end()

Returns: static

endsWith

SHORTCUT Model::like($property,"%$value")

EnsureDateTime

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 $value Some value representing a datetime

  • bool $convert_now_to_value if true will check if $value=='now()' and if so return new DateTimeEx instead of 'now()'

enumerate

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_fieldname Property-/Fieldname

  • bool $distinct If true will array_unique the results.

  • string $key_column_name If given uses this column as key for an associative resulting array

eq

SHORTCUT Model::equal($property,$value,$value_is_sql)

equal

Check if a field has a value.

Definition: public function equal($property, $value, $value_is_sql=false)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

  • mixed $value Value to check for

  • bool $value_is_sql if true, $value is treaded as SQL keyword/function/... and will remain unescaped (sample: now())

FieldValues

Returns column values.

Definition: public function FieldValues($args)

Returns: array plain array of values

Parameters:

  • mixed $args Column names

Find

Selects Models from the database with a partial SQL statement.

Definition: public function Find($where, $prms)

Returns: array Array of Model datasets

Parameters:

  • string $where WHERE-part of the SQL statement.

  • array $prms Arguments used in $where

FullQualifiedFieldName

Creates a full qualified fieldname. That is ```tablename`.field_name``

Definition: public function FullQualifiedFieldName($name)

Returns: string FQ fieldname

Parameters:

  • string $name Name to FQ

GetChanges

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

GetColumnNames

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_only Return only changed columns names

GetPagingInfo

SHORTCUT ResultSet::GetPagingInfo

GetPrimaryColumns

Returns the names of all primary columns.

Definition: public function GetPrimaryColumns()

Returns: array List of all columns that belong to the primary key

GetTableName

Derivered classes must implement this and return the table name they are stored in.

Definition: public abstract function GetTableName()

Returns: string Table name

GetTableSchema

Returns the TableSchema of this Model.

Definition: public function GetTableSchema()

Returns: TableSchema

greaterThan

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 $property Property-/Fieldname

  • mixed $value Value to check against

  • bool $value_is_sql if true, $value is treaded as SQL keyword/function/... and will fremain unescaped (sample: now())

greaterThanOrEqualTo

Check if a fields value is greater than or equal to something.

Definition: public function greaterThanOrEqualTo($property, $value)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

  • mixed $value Value to check against

groupBy

Adds a groupBy statement to the query.

Definition: public function groupBy($property)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname to group by

gt

SHORTCUT Model::greaterThan($property, $value)

gte

SHORTCUT Model::greaterThanOrEqualTo($property, $value)

HasChanged

Checks if a column has changed.

Definition: public function HasChanged($col)

Returns: bool true if changed, else false

Parameters:

  • string $col Name of the column to check

HasColumn

Checks if this Model has a column $name.

Definition: public function HasColumn($name)

Returns: bool true or false

Parameters:

  • string $name Column name to check for

HasValue

Checks if there's a value set for the given column.

Definition: public function HasValue($name)

Returns: bool

Parameters:

  • string $name Column name

having

Adds a HAVING statement.

Definition: public function having($defaultOperator)

Returns: Model clone $this

Parameters:

  • string $defaultOperator 'AND' or 'OR'

in

Checks if a fields value is one of the $values.

Definition: public function in($property, $values)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

  • array $values Array of values to check against

isDateInRange

Filters by "the given date is between start & end".

Definition: public function isDateInRange($startfieldname, $endfieldname, $date=false)

Returns: Model $this

Parameters:

  • string $startfieldname Name of the column containing the start date(-time)

  • string $endfieldname Name of the column containing the end date(-time)

  • mixed $date The date value to be chacked against

isFuture

SHORTCUT Model::newerThan($property,0,'second') Filters by date values in the future

isNull

Checks if a fields value is NULL.

Definition: public function isNull($property)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

isPast

SHORTCUT Model::olderThan($property,0,'second')

IsQuery

Returns true is this is a query, false if this represents a datatset

Definition: public function IsQuery()

Returns: bool true or false

IsRow

Returns true is this is a dataset, false if this represents a query

Definition: public function IsRow()

Returns: bool true or false

join

Join two database tables.

Definition: public function join($direction, $model)

Returns: Model clone $this

Parameters:

  • string $direction E.g. 'LEFT', 'RIGHT' or 'FULL'. Also 'LEFT OUTER'.

  • Model $model An instance of a Model subclass.

key

IMPLEMENTS Iterator::key

like

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 $property Property-/Fieldname

  • mixed $value Value to check against

  • bool $flipped If true, expects the roles of $property and $value switched

limit

SHORTCUT Model::page(0,$limit);

Load

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 $where WHERE-part of the SQL statement.

  • array|mixed $arguments Arguments used in $where

LogDebug

SHORTCUT ResultSet::LogDebug

lowerThan

Check if a fields value is lower than something.

Definition: public function lowerThan($property, $value)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

  • mixed $value Value to check against

lowerThanOrEqualTo

Check if a fields value is lower than or equal to something.

Definition: public function lowerThanOrEqualTo($property, $value)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

  • mixed $value Value to check against

lt

SHORTCUT Model::lowerThan($property, $value)

lte

SHORTCUT Model::lowerThanOrEqualTo($property,$value)

Make

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 $datasource DataSource to bind to, defaults to Model::$DefaultDatasource

  • mixed $pk_value Primary key value

MakeFromData

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 $data Associative array with data

  • DataSource $datasource Optional datasource to assign to the created Model

  • bool $allFields If true, all data is taken to the result, not only that one that are present in the columns of the type

  • bool $className Optional classname to allow anonymous calls like Model::MakeFromData

neq

SHORTCUT Model::notEqual($property,$value)

neqBinary

Check if a fields value is binary NOT equal to another value.

Definition: public function neqBinary($property, $value)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

  • mixed $value Value to check against

newerThan

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 $property Properpy-/Fieldname

  • int $value Offset value

  • string $interval Unit

next

IMPLEMENTS Iterator::next

noop

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

notBinary

Check if a field has NOT a BINARY value.

Definition: public function notBinary($property, $value)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

  • mixed $value Value to check for

notEqual

Check if a field has NOT a value.

Definition: public function notEqual($property, $value)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

  • mixed $value Value to check for

notIn

Checks if a fields value is NOT one of the $values.

Definition: public function notIn($property, $values)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

  • array $values Array of values to check against

notNull

Checks if a fields value is NOT NULL.

Definition: public function notNull($property)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

offsetExists

IMPLEMENTS ArrayAccess::offsetExists

offsetGet

IMPLEMENTS ArrayAccess::offsetGet

offsetSet

IMPLEMENTS ArrayAccess::offsetSet

offsetUnset

IMPLEMENTS ArrayAccess::offsetUnset

olderThan

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 $property Properpy-/Fieldname

  • int $value Offset value

  • string $interval Unit

orAll

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

orderBy

Adds a orderBy statement to the query.

Definition: public function orderBy($property, $direction, $checkfieldname=true)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname to order by

  • string $direction 'ASC' or 'DESC'

  • bool $checkfieldname Check the fieldname or not (true|false)

orX

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 $count How many following calls shall be OR-combined

ot

SHORTCUT Model::olderThan($property, $value, $interval)

page

Adds paging to the query.

Definition: public function page($offset, $items)

Returns: Model clone $this

Parameters:

  • int $offset Zero-based offset

  • int $items Maximum items to return

process

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 $callback Anonymous callback function

Query

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 $sql Statement

  • array $args Arguments

  • DataSource $datasource Use this datasource

results

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)

rewind

IMPLEMENTS Iterator::rewind

rlike

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 $property Property-/Fieldname

  • mixed $value Value to check against

  • bool $flipped If true switches the roles of $property and $value

SanitizeValues

DEPRECATED (2022/07) This uses a non existant function, so atm does nothing Uses <system_sanitize_parameters> to sanitze all field values.

Save

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'],...]

scalar

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 $property Property name

  • mixed $default Default if nothing was found

Select

SHORTCUT Model::Make($datasource)

shuffle

Like Model::orderBy but adds 'ORDER BY rand()'.

Definition: public function shuffle()

Returns: Model clone $this

sql

Adds a raw SQL part to the statement.

Definition: public function sql($sql_statement_part, $args)

Returns: Model clone $this

Parameters:

  • string $sql_statement_part The raw SQL code

  • array $args The arguments of the raw SQL query part

startsWith

SHORTCUT Model::like($property,"$value%")

TryGetClassFromTablename

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 $tablename The name of the table

  • DataSource $ds Optional datasource to use.

TypedValue

INTERNAL Wrapper around private method to allow overriding without breaking internal functionality

TypeOf

INTERNAL Wrapper around private method to allow overriding without breaking internal functionality

Update

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 $args The columns names to save

valid

IMPLEMENTS Iterator::valid

youngerThan

SHORTCUT Model::newerThan($property, $value, $interval)

yt

SHORTCUT Model::newerThan($property, $value, $interval)

__log_dynamic_property_access

Definition: protected function __log_dynamic_property_access($name)

Returns: NOT DOCUMENTED

Parameters:

  • $name NOT DOCUMENTED
Clone this wiki locally