zajModel


zajModel is the base class for all Outlast Framework models. Below is an overview of the properties, settings, events, and methods you will have access to when you extend zajModel.

For basic examples of how to create model classes see the getting started guide, the Sample class in the default Outlast Framework install, or the Todo List example app.

Properties

All models will have the following properties:

  • name – a cached field of the name of the item.
  • id – a cached field of the id of the item.
  • name_key – the field name for the ‘name’.
  • model – stores the field types as an associative array
  • exists – this is true if the object exists in the database. false if it is new.
  • class_name – the name of the model.
  • table_name – the name of the table as stored in the database (usually lower-case of the model).
  • id_column – the name of the id column. defaults to ‘id’.
  • data – an object that contains all model data, preprocessed and ready to use. internally this is actually a zajData object. as soon as you use the data property, the database will be hit once for that object. this is really quick, but something to keep in mind nonetheless. you can use cached fields and fetchdata to speed things up if needed.
  • fetchdata – an object that contains any additional data fetched during a custom SQL query
  • translation – for localized fields this is the translated data. see documentation for more details.

In addition, each model can have cached properties. These are defined in the __afterFetch() magic method and are stored in cache instead of in the database. Each save() triggers a cache refresh or you can use the uncache() method. Caches can also be cleared via the cache library.

You can access properties like you would on any PHP object:

$user = User::fetch();
echo $user->name;

Or in template syntax:

{{user.name}}

Settings

Model settings can be used to change the default behaviour of model objects.

  • in_database – set to true if this object should be stored in the database. Defaults to true.
  • has_translations – set to true if this object should have translations associated with it. Defaults to true.
  • fetch_order – set to DESC or ASC depending on the default fetch sort order. Defaults to DESC.
  • fetch_order_field – set to the field which should be the default fetch sort field. defaults to ‘ordernum’.
  • fetch_paginate – set the number of items to display when listed or leave as unlimited. Defaults to 0, which is unlimited. Changing this can have unintended consequences, use with care!

Settings are stored as static variables, so you can declare them at the top of your model class:

class Country extends zajModel {
	/**
	 * Set to DESC or ASC depending on the default fetch sort order.
	 * @var string
	 **/
	public static $fetch_order = 'DESC';
	/**
	 * Set to the field which should be the default fetch sort field.
	 * @var string
	 **/
	public static $fetch_order_field = 'ordernum';
	
	/** Rest of your class implementation goes here! **/
}

Magic methods / events

There are two types of magic methods for zajModel classes. First there are magic methods that define the model behavior, second there are magic methods that serve as callback methods before and after certain events (like when an object is created or saved).

Definition methods

You can use these methods to define your model’s structure and behavior:

  • stdClass __model($fields) This method defines and returns the model structure. Each field is defined as a zajDb object (see docs). See the Sample class included in a basic OFW install, take a look at the todolist example, and check out the list of data types to get an overview of how to use this method. Returns a list of keyvalue pairs where each key is the name of the field and each value is a zajDb object.
  • zajField __field($field_name) This method returns a zajField object for a specific field.

Event callback methods

You can use these methods to execute code before or after certain events:

  • boolean __beforeCreateSave() Executed before the object is first created in the database. If returns false, the object is not saved!
  • boolean __beforeSave() Executed before the object is saved to the database. If returns false, the object is not saved!
  • boolean __beforeCache() Executed before the object is saved to a cache file. If returns false, the object is not cached!
  • boolean __beforeUncache() Executed before the object cache is removed. If it returns false, the object cache will not be removed! Note: This is not called in every situation!
  • boolean __beforeDelete() Executed before the object is deleted. If returns false, the object is not deleted!
  • void __afterCreateSave() Executed after the object is created in the database.
  • void __afterCreate() Executed after the object is created in memory.
  • void __afterSave() Executed after the object is saved to the database.
  • void __afterFetch() Executed after the object is fetched from the database (and NOT from cache). Also fired after save.
  • void __afterFetchCache() Executed after the object is fetched from a cache file. Note that this is also fired after a database fetch.
  • void __afterCache() Executed after the object is saved to a cache file.
  • void __afterUncache() Executed after the object cache is removed (but only if the remove was successful) Note: This is not called in every situation!
  • void __afterDelete() Executed after the object is deleted.
  • void __onFetch() Executed when a fetch method is requested.
  • void __onCreate() Executed when a create method is requested.
  • zajFetcher __onSearch(zajFetcher $fetcher, string $type) Executed when the search API is used on the class.
  • boolean __onSearchFetcher(zajFetcher &$fetcher, string $query, boolean $similarity_search = false, string $type = 'AND') Executed when search() is run on the model’s zajFetcher object. If it returns boolean false (default) it is ignored and the default search() is applied.
  • boolean __onFilterQueryFetcher() __onFilterQueryFetcher(zajFetcher &$fetcher, string $query, boolean $similarity_search = false, string $type = 'AND') Executed when filter_query() is run on the model’s zajFetcher object. If it returns boolean false (default) it is ignored and the default filter query is applied.

* @method static zajFetcher __onSearchFetcher() __onSearchFetcher(zajFetcher &$fetcher, string $query, boolean $similarity_search = false, string $type = ‘AND’) EVENT. Executed when search() is run on the model’s zajFetcher object. If it returns boolean false (default) it is ignored and the default search() is applied.

Magic properties

Typically, “regular” properties that you define on your zajModel object are cached properties. Built-in examples of this are the name and id properties, both of which are cached and available directly via $object->name or {{object.name}}. These have a single value, which is stored and cached whenever set() and save() are called (see docs on cacheing for more info).

Sometimes you may want to expose properties that will not be cached but will be calculated at runtime, because their values are dynamic. These are known as dynamic properties or magic properties and can be created using PHP’s standard __get() magic method.

A typical example of this is when you want a property to be dependent on the current user, such as to see if the user has certain rights or associations with the given model object.

Here’s an example where we expose a property that returns whether or not the current user is an owner of this object:

static fetch()

Fetch a single or multiple existing object(s) of this class.

// Fetch a single item (zajModel)
$sample = Sample::fetch($_GET['id']);
// Fetch a list of all items (zajFetcher)
$samples = Sample::fetch();

bool|string|zajModel $id [optional] The id of the object. Leave empty if you want to fetch multiple objects. You can also pass an existing zajModel object in which case it will simply pass through the function without change – this is useful so you can easily support both id’s and existing objects in a function.
@return zajFetcher|self Returns a zajFetcher object (for multiple objects) or a zajModel object (for single objects).

static create()

Create a new object in this model.

// Create a new item
$new_sample = Sample::create();
// Create a new item with a specific id
$new_sample = Sample::create('my_id');

bool|string $id [optional] Id’s are automatically generated by default, but you can force one here. Once created, id’s cannot be changed. If you set the id, you are responsible for making it unique.
@return zajModel Will return a new model object.

set()

Set the value of a field for this object. Does not write it to the database until you call save().

$sample->set('name', $_GET['name'])->set('something', $_GET['something'])->save();

string $field_name The name of model field.
mixed $value The new value of the field.
@return zajModel Returns itself, so you can chain methods.

set_these()

Sets all the fields specified by the list of parameters. It uses GET or POST requests, and ignores fields where no value was sent (that is, not even an empty value). In cases where you need more control, use {@link set()} for each individual field.

string $field_name1 The first field to set.
string $field_name2 The second field to set.
string $field_name3 The third field to set…etc.
@return zajModel Returns itself, so you can chain methods.

set_with_data()

Sets all fields of model data based on a passed associative array or object.

@param array|stdClass $data The data to create from. This can be a standard class or associative array.
@return zajModel Returns me to allow chaining.

set_translation()

Set the translation value of a field for this object.

$sample->set_translation('name', 'Ez a neve', 'hu_HU')->save();

string $field_name The name of model field.
mixed $value The new value of the field.
string $locale The locale for which to set this translation.
@return zajModel Returns itself, so you can chain methods.

set_translations()

Sets the translation of all the locales of all the fields specified by the list of parameters. It uses GET or POST requests, and ignores fields where no value was sent (that is, not even an empty value). In cases where you need more control, use {@link set_translation()} for each individual field.

An example POST request would be sent as $_POST[‘translation’][‘name’][‘hu_HU’]. You can use the {% inputlocale %} tag to generate proper inputs (see docs).

string $field_name1 The first field to set.
string $field_name2 The second field to set.
string $field_name3 The third field to set…etc.
@return zajModel Returns itself, so you can chain methods.

save()

Save the values set by {@link: set()} to the database.

boolean $events_and_cache [optional] If set to true, the before and after events and cacheing will be fired. If false, they will be ignored. This is useful when you are trying to speed things up (during import of data for example).
@return zajModel|boolean Returns the chainable object if successful, false if beforeSave prevented it.

duplicate()

Creates a duplicate copy of the object. Connections are not duplicated by default and the new object is not saved to the db, just returned.

bool|string $id Id’s are automatically generated by default, but you can force one here. Once created, id’s cannot be changed. You must ensure uniqueness if set manually.
@return zajModel Returns a new, unsaved object whose fields are set to the same data values.

to_array()

Convert model data to a standard single-dimensional array format. Connections are not exported.

@return array Return a single-dimensional array.

delete()

Set the object status to deleted or remove from the database.

boolean $permanent [optional] If set to true, object is permanently removed from db. Defaults to false.
@return boolean Returns true if the item was deleted, false if beforeDelete prevented it.

static delete_tests()

A static method which deletes all objects that were created during unit testing.

integer $max_to_delete The maximum number of objects to remove. Defaults to 3. Fatal error if more than this amount found.
boolean $permanent If set to true, object is permanently removed from db. Defaults to true.
@return integer Returns the number of objects deleted.

static reorder()

Reorder the item’s ordernum based on the order of ids in the passed array.

array $reorder_array An array of object ids.
bool $reverse_order If set to true, the reverse order will be taken into account.
@return bool Always returns true.

fire()

Fire an event magic method.

string $event Event name.
array|bool $arguments Array of parameters. Leave empty if no params.
@return mixed Returns the value returned by the event method.

static fire_static()

Fire a static event magic method.

string $event The name of the event.
array|bool $arguments Array of parameters. Leave empty if no params.
@return mixed Returns the value returned by the event method.

cache()

Create a cached version of the object. Cache is currently stored as a file but memcached support is coming.

@return zajModel|boolean Returns the chainable object if successful, false if beforeCache prevented it.

uncache()

Remove a cached version of an object. You can clear object caches at anytime from the update menu found at http://example.com/update/.

@return zajModel|boolean Returns the chainable object if successful, false if beforeUncache prevented it.

static get_cache()

Gets the cached version of an object. Do not use this directly unless you truly need to! Use fetch() methods instead. This may become a private method eventually.

string $id The id of the object.
@return zajModel Returns the object.

static extension()

This method returns the class name of the class which extends me.

@return string The name of my extension class.

Outlast Web & Mobile Development (c) 2023 | Privacy Policy |