NanoMVC

Models

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 are stored in the models directory. Here's a basic example:

/myapp/
  /models/
    page_model.php
class Page_Model extends NanoMVC_Model {
  function get_title() {
    return 'Hello';
  }

  function get_body_text() {
    return 'Hello World.';
  }
}

The model class name must match the filename (case-insensitive). The _model suffix is optional but helps with organization.

To use a model from a controller:

class Hello_Controller extends NanoMVC_Controller {
  public Page_Model $page; // Declare the model property

  function index() {
    $this->load->model('Page_Model', 'page'); // declared model property
    // The connection is cached; to reconnect, set $this->page = null

    $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');
  }
}

By default, the model will use the default pool from the database configuration. You may load from a specific connection pool like this:

$this->load->model('Page_Model', 'page', null, 'mypool');

Multiple connection pools are supported and defined in your config_database.php file.

Using the PDO database layer

NanoMVC uses PDO for database access. Example:

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

Or:

function get_member($id) {
  return $this->db->query_one('select * from members where id = ?', [$id]);
}

Or:

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

You can pass PDO::FETCH_ASSOC, PDO::FETCH_NUM or PDO::FETCH_BOTH as a third parameter in query methods.

Build complex queries:

function get_members() {
  $this->db->select('my.foo, my.bar, my.baz'); // select specific columns from the database
  $this->db->from('mytable my'); // set the table to select data from (alias "my")
  $this->db->where('my.foo', 'test'); // add a WHERE condition: my.foo = 'test'
  $this->db->orwhere('my.foo = ? and my.bar = ?', ['test', 'test2']); // add an OR condition using parameter binding for security
  $this->db->join('jointable j', 'j.foo = my.foo', 'LEFT'); // add a LEFT JOIN with "jointable" on the condition j.foo = my.foo
  $this->db->in('my.column', ['any1', 'any2'], false); // add a WHERE IN clause with values quoted safely using PDO
  $this->db->orin('my.other_column', 'val1, val2', true); // add an OR IN clause with raw values — only use if you're sure inputs are safe
  $this->db->orderby('my.ordercolumn, j.ordercolumn desc'); // add ORDER BY clause to sort the results
  $this->db->groupby(​'my.groupbycolumn'); // add GROUP BY clause to group the results
  $this->db->limit(20, 0); // limit the result to 20 rows starting from offset 0
  $this->db->query(); // execute the assembled query
  while($row = $this->db->next()) $rows[] = $row;
  return $rows;
}

NanoMVC includes a lightweight ORM plugin, and you can also define your own by setting $config['default']['plugin']. You may also use raw queries directly.

Examples:

$this->db->query_all('select * from members where foo = ? and bar = ?', ['test', 'test2']);
$this->db->where('id', 1);
$this->db->update('tablename', ['col1' => 'val1']);

Returns true on success.

$this->db->insert('tablename', ['col1' => 'val1']);

Returns inserted ID.

$this->db->where('id', 1);
$this->db->delete('tablename');

Returns true on success. Always use WHERE with delete() to avoid wiping entire tables.

Available methods

Access PDO object directly

If you want to use the PDO object directly, it is available as $this->db->pdo. This allows you to use full PDO functionality, but you'll need to handle syntax, quoting, and errors manually.

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

Database Configuration

$config['default']['plugin']     = 'NanoMVC_PDO';
$config['default']['type']       = 'mysql';
$config['default']['host']       = 'localhost';
$config['default']['name']       = 'dbname';
$config['default']['user']       = 'dbuser';
$config['default']['pass']       = 'dbpass';
$config['default']['persistent'] = false;
$config['default']['charset']    = 'utf8mb4';
$config['default']['port']       = 3306; // optional
$config['default']['schema']     = 'public'; // for PostgreSQL
$config['default']['dsn']        = ''; // overrides all dsn settings inside

You may define multiple pools: $config['default'], $config['mypool'], etc.

Note: The NanoMVC_PDO plugin is officially tested with MySQL and PostgreSQL. Other PDO-supported drivers (like sqlite, sqlsrv, etc.) may work but are not guaranteed or supported by default.

← to Views to Plugins →

← Back to Documentation