Documentation:Models

From TinyMVC Documentation

Jump to: navigation, search

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.

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 abtraction layer for database access, which is included with PH5 5.1 and up. Be sure you have your myapp/configs/database.php setup for your database.

Lets try an example:

members_model.php

class Members_Model extends TinyMVC_Model
{
  function get_members()
  {
    $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->where('foo','test'); // where foo='test'
    $this->db->orwhere('foo=? and bar=?',array('test','test2')) // where foo='test' and bar='test2'
    $this->db->join('jointable','mytable','jointable.foo=mytable.foo'); // join tables on (optional) condition
    $this->db->in('mycolumn',$elements,$islist,$prefix) // IN clause: column, elements (comma-separated or array), $list=boolean is list or array, $prefix: AND|OR
    $this->db->orderby('ordercolumn'); // order by column(s)
    $this->db->groupby('groupbycolumn'); // group by column(s)
    $this->db->limit($limit,$offset); // query limit, optional offset
    $this->db->query();
    while($row = $this->db->next()) {
      $rows[] = $row;
    }
    return $rows;
  }
}

The model wrapper allows you to build your query programmatically, much like active record.


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

  • $this->db->query($sql,$params) executes a query to loop over results with $this->db->next()
  • $this->db->query_one($sql,$params,$format) returns one result record
  • $this->db->query_all($sql,$params,$format) returns all result records
  • $this->db->next($format) used to loop over a result set
  • $this->db->last_insert_id() gets the last insert id from the database
  • $this->db->num_rows() returns the number of records from the last query

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. Example:

class Members_Model extends TinyMVC_Model
{
  function get_members()
  {
    $results = null;
    try {
      foreach ($this->db->pdo->query('SELECT * from members') as $row)
        $results[] = $row;
      $this->db->pdo = null;
    } catch (PDOException $e) {
      trigger_error($e->getMessage());
      return false;
    }
    return $results;    
  }
}
Personal tools