Creating, modifying and loading data with models


Models = tables

In order to use data models in your application (quite likely that you will want to:)) you first have to enable and configure the database connection options in the proper section of site/index.php. This is commented in the document, so take a look!

Next, you’ll need to create a sample model, but one is actually already available to you in the project you downloaded. You’ll find it as /app/mode/sample.model.php.

Let’s take a look at the first part of the source:

class Sample extends zajModel {

  /**
   * __model function. creates the database fields available for objects of this class.
   * 
   */
  public static function __model(){
    /////////////////////////////////////////
    // begin custom fields definition:
      $f = new stdClass();
      $f->name = zajDb::name();
      $f->description = zajDb::text();
      $f->photos = zajDb::photos();
    // end of custom fields definition
    /////////////////////////////////////////   

    // do not modify the line below!
      $f = parent::__model(__CLASS__, $f); return $f;
  }
  /** more stuff here that we'll ignore for now **/
}

Each model file has a __model() magic method which serves as the definition of the data fields available in that model. Here we have three fields: a name (type name), a description (type text), and some photos (type photos). We’ll just leave the default as it is for now.

Creating the database automatically

Now you’ll want to create the database structure for this application, so just visit http://www.example.com/update/ – this is the central web-based hub for updating your application, clearing its caches, running unit tests, etcetc. On a live site you should either password protect or disable this feature, but for development this is very useful and allows you to avoid the command line altogether.

If you’ve enabled the database correctly you’ll see the Database update feature on the left – click it to create your application’s empty database structure. You will also need to run this after any changes to your model files as this feature will update your database with any new fields, or rename fields as needed. While the update feature is generally safe, you should of course ALWAYS back up data before running a database update.

Creating data

Let’s use this Sample model to create some random example data and save it to the database.

To create some items, you’ll need to run the code below. Create a new function create_test() in your default controller default.ctl.php and add this code:

function create_test(){
  // First use the create static method to create a new object
  $sample1 = Sample::create();
  // Now set the fields
  $sample1->set('name', 'My First Sample Object');
  $sample1->set('description', 'This is just a random sample object.');
  // Finally save it to the database
  $sample1->save();

  // Repeat with another one...
  $sample2 = Sample::create();
  $sample2->set('name', 'Another Sample Object');
  $sample2->set('description', 'It cant hurt to have more than one...');
  $sample2->save();

  // Now print some result
  print "All done.";
}

Now visit http://www.example.com/create/test/ in your browser and you should see ‘All done.’. If you now check the database with phpmyadmin or some other tool you’ll see that we have two rows of data in the Sample table.

Automatic fields

If you did check with phpmyadmin, you’ll notice that a few extra automatic fields have also been added. These include:

  • id – The unique id of the object generated by the php uniq(”) function.
  • status – Defaults to an enum field of type ‘new’,’deleted’. Items in the ‘deleted’ status are not automatically fetched in lists. More on that in a minute…
  • ordernum – This field tracks the default sort order of the items. It is incremented by order of creation.
  • time_create – A UNIX timestamp of when the item was created.
  • time_edit – A UNIX timestamp of when the item was updated.
  • unit_test – A boolean which will be true if the object was created during a unit test. Fields marked true will be removed on zajModel::delete_tests(). You cannot modify this field.

These automatic fields are handled by the framework and you do not need to edit them manually.

Listing and fetching data

You can fetch data in two ways: get a single item by id or get a list of items filtered by specific parameters.

Let’s see some examples for listing items…

$list_of_all_samples = Sample::fetch(); // Get's all the Sample objects
$list_of_filtered_samples = Sample::fetch()->filter('name', '%First%'); // Get's all the Sample objects that contain 'First' in their name-s

// Once you have a list, you can then foreach through it as if it were an array (it's actually a zajFetcher object)
foreach($list_of_all_samples as $sample){
  // Each of the sample's data fields can be accessed via the 'data' property...
  print $sample->data->name."
";
}

And some examples for single items…

$a_specific_sample_item = Sample::fetch('aW23sd3234'); // Get a sample object with id 'aW23sd3234'
$the_first_in_the_list_of_filtered_samples = Sample::fetch()->filter('name', '%First%')->next(); // Get the first item in the filtered list

// Now we have a single sample item, so just print it!
print $a_specific_sample_item->data->name;

Defining models and data fields

Model classes have a very specific structure that you must adhere to:

  • They must be in one of the /model/ folders (usually /app/model/) and be named as myname.model.php
  • The class name must be the same as the model name and it must extend zajModel
  • Model fields must be defined in the static __model method.
  • For now, it must also contain the __construct and __callStatic methods. This will be removed in a future version.

Check out the Sample model default for reference:

Defining model fields

Model field data types are very cool, because not only will it automate fetching and filtering data on the field, it will also generate inputs for your admin interface based on the type. For example, a type of ‘photos’ will actually generate a photo upload field – one that you can display and save really easily…

When you define model fields in the model class’s __model method, you must give it a name and a field data type as follows:

$f->description = zajDb::text();

The variable’s name will be the field name (description) and the zajDb class will be used to define it’s data type (text). There are many built in data types but you can also define your own types – more on this later.

To see a full list of available data types, check out the API docs.

There are quite a lot of built-in field types, including relationships of various sorts (photos, maps, ratings, etc.). Field types can make working with multiple tables a pleasure – it just works, without having to think about it.

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