Welcome to TinyMVC, the tiny PHP Framework.

Models

Contents

What is a model?

Models are the layer of the MVC that are used to aggregate data. The underlying data source is typically a database, although this can be any type of source such as a flat file.

Learning by example

Model files live in the models directory. Lets create a model:

/myapp/
  /models/
    page_model.php

page_model.php

class Page_Model extends TinyMVC_Model
{
  function get_title()
  {
    return 'Hello';
  }
  function get_body_text()
  {
    return 'Hello World.';
  }
}

The model file name must match the model class name. The class can be any case, but the file name must be lower case.
The _model extension is not required, but it helps keep things organized.

Declare any properties your model uses, such as var $cache = array();. PHP 8.2 and later deprecate creating undeclared properties, and the TinyMVC error handler reports that as an error.

We load models from within the controller. Lets try an example:

/myapp/controller/hello.php

class Hello_Controller extends TinyMVC_Controller
{
  function index()
  {
    // load the model
    $this->load->model('Page_Model','page');
    // alternately, specify the connection pool (default is "default")
    // $this->load->model('Page_Model','page',null,'mypool');
 
    // use the model to gather data
    $title = $this->page->get_title();
    $body_text = $this->page->get_body_text();
 
    $this->view->assign('title',$title);
    $this->view->assign('body_text',$body_text);
    $this->view->display('hello_view');
  }
}

The first parameter to $this->load->model() is the model class name. The second parameter is an optional alias name. This loads the model into a class property, then you use it to gather data. If you kept the same view file from the previous chapter, you should see the same result except this time the assigned data came from a model.

Using the PDO database layer

TinyMVC uses the PDO database abstraction layer for database access. Be sure your myapp/configs/config_database.php is set up for your database.

Lets try an example:

members_model.php

class Members_Model extends TinyMVC_Model
{
  function get_members()
  {
    $results = array();
    $this->db->query('select * from members');
    while($row = $this->db->next())
      $results[] = $row;
    return $results;
  }
}

Assuming you have a database with a table named members, the above get_members() method would return all the records in the members table.

class Members_Model extends TinyMVC_Model
{
  function get_member($id)
  {
    return $this->db->query_one('select * from members where id=?',array($id));
  }
}

The above gets one record from the database. This example shows how to use a variable passed into the method as a query parameter. query_one() returns one record.

class Members_Model extends TinyMVC_Model
{
  function get_members()
  {
    return $this->db->query_all('select * from members');
  }
}

query_all() returns all records from a query. This is essentially the same as the first query() example.

You can optionally pass a format value of PDO::FETCH_ASSOC, PDO::FETCH_NUM, or PDO::FETCH_BOTH. PDO::FETCH_ASSOC is default.

class Members_Model extends TinyMVC_Model
{
  function get_members()
  {
    $this->db->select('foo,bar,baz'); // set selected columns
    $this->db->from('mytable');  // set from what table(s)
    $this->db->join('jointable','jointable.foo=mytable.foo','LEFT'); // join table on condition, optional join type
    $this->db->where('foo','test'); // where foo='test'
    $this->db->orwhere('foo=? and bar=?',array('test','test2')); // or foo='test' and bar='test2'
    $this->db->in('mycolumn',$elements); // and mycolumn IN (...), elements are an array or comma-separated string
    $this->db->orin('othercolumn',$elements); // or othercolumn IN (...)
    $this->db->groupby('groupbycolumn'); // group by column(s)
    $this->db->orderby('ordercolumn'); // order by column(s)
    $this->db->limit($limit,$offset); // query limit, optional offset
    $this->db->query();
    $rows = array();
    while($row = $this->db->next())
      $rows[] = $row;
    return $rows;
  }
}

The model wrapper allows you to build your query programmatically, much like active record. The values given to where(), orwhere(), in() and orin() are escaped for you. If you pass true as the third parameter of in() or orin(), the elements are inserted as raw SQL (such as a subquery) and are not escaped.


class Members_Model extends TinyMVC_Model
{
  function get_members()
  {
    return $this->db->query_all('select * from members where foo=? and bar=?',array('test','test2'));
  }
}

The ? syntax passes arguments to the query which are automatically sql-escaped. ?'s can also be used in other functions such as where() and orwhere().

class Members_Model extends TinyMVC_Model
{
  function get_members()
  {
    $this->db->where('foo','bar'); // setup query conditions (optional)
    return $this->db->update('tablename',array('col1'=>'value','col2'=>'value',...));
  }
}

Update a table with the update() command.

class Members_Model extends TinyMVC_Model
{
  function get_members()
  {
    return $this->db->insert('tablename',array('col1'=>'value','col2'=>'value',...));
  }
}

Insert into a table with the insert() command.

class Members_Model extends TinyMVC_Model
{
  function delete_members()
  {
    $this->db->where('id !=',1); // setup query conditions (optional)
    return $this->db->delete('tablename');
  }
}

Delete from a table with the delete() command.


Available functions:

Access PDO object directly

If you want to use the PDO object directly, it is available as $this->db->pdo. This way you can take full advantage of all of the PDO features, but you must abide by its syntax and rules. TinyMVC sets PDO to throw a PDOException on errors. Example:

class Members_Model extends TinyMVC_Model
{
  function get_members()
  {
    $results = array();
    foreach($this->db->pdo->query('SELECT * from members') as $row)
      $results[] = $row;
    return $results;
  }
}
TinyMVC is licensed under the GNU LGPL license.
This page was rendered in 0.00030 seconds.