Skip to content
This repository

classes_essentials_model_model.class 

DaSpors edited this page · 6 revisions

Pages 173

Clone this wiki locally

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;  

Namespace: ScavixWDF\Model

Implements: Iterator Countable ArrayAccess

Subclasses: CommonModel

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

Returns: array Associative array of fieldname=>value pairs

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)

Returns: subclass_of_Model The typed object

Parameters:

  • Model $model Object of (sub-)type Model

count

Returns the amount of results in the current query.

Definition: public function count()

Returns: int Amount of results

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: boolean true or false

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)

Returns: array Array of values

Parameters:

  • string $property_or_fieldname Property-/Fieldname

  • bool $distinct If true will array_unique the results.

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 fremain unescaped (sample: now())

FieldValues

Returns all column values.

Definition: public function FieldValues()

Returns: array plain array of values

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

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

greaterThan

Check if a fields value is greater than something.

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

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname

  • mixed $value Value to check against

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)

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

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

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: boolean true if dataset was found, else false

Parameters:

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

  • array $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: Model 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)

Returns: subclass_of_Model The newly created typed Model

Parameters:

  • array $data Associative array with data

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

neq

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

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

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)

Returns: Model clone $this

Parameters:

  • string $property Property-/Fieldname to order by

  • string $direction 'ASC' or 'DESC'

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

Uses to sanitze all field values.

Definition: public function SanitizeValues()

Returns: void

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)

Returns: boolean In fact always true, WdfDbException will be thrown in error case

Parameters:

  • array $columns_to_update If given only these fields will be updated. If not Model tries to detect changed columns automatically.

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:

  • 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

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 array 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()

Returns: Model clone $this

valid

IMPLEMENTS Iterator::valid

youngerThan

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

yt

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

Something went wrong with that request. Please try again.