Models are classes that are designed to handle the data of your application. One example could be a class that can insert, update, fetch and delete articles from your database. All models should be located in the app/models directory.
Mako does not include any ORM functionality but if you want to use ORM then its easy to integrate Doctrine or similar solutions into your application (doctrine example is included in app/bootstrap.php).
Mako does not force you to use models and you are not required to extend the model class described in this document.
Creating a model object is done by using the constructor.
// Creates a new model object using the "default" connection;
$news = new News();
// Creates a new model object using the "foobar" connection;
$news = new News('foobar')
You are not required to define a constructor for your models but if you plan to extend the Mako default model and need to override the default constructor then you'll have to replicate the method signature of the parent constructor and call the parent constructor like this:
public function __construct($connection = null)
{
// Call the parent constructor
parent::__construct($connection);
// Your custom code goes here
}
The factory method returns a model object. This allows you to chain methods.
$articles = News::factory()->getAll();
Here's a simple example of what a model can look like.
<?php
namespace app\models
{
class News extends \mako\Model
{
public function add($title, $body, $date)
{
return $this->connection->table('news')
->insert(array('title' => $title, 'body' => $body, 'date' => $date));
}
public function get($id)
{
return $this->connection->table('news')
->where('id', '=', $id)
->first();
}
public function getAll()
{
return $this->connection->table('news')
->orderBy('id', 'desc')
->all();
}
public function update($id, $title, $body)
{
return (boolean) $this->connection->table('news')
->where('id', '=', $id)
->update(array('title' => $title, 'body' => $body));
}
public function delete($id)
{
return (boolean) $this->connection->table('news')
->where('id', '=', $id)
->delete();
}
}
}
Using the model in your controller would be as simple as this:
$news = new News();
$news->add('Hello World!', 'This is just a test.', time());