Version 5, last updated by pagchen at November 07, 2011 23:43 UTC
7 Our first model
This wiki has been updated for version 0.7-alpha4
Models explained
Getting data
A model aggregates data from one or more data sources. This encapsulates the data, so the rest of your code doesn't need to know what the data sources are, how to extract data from them, and how to format it in a usable way. Whenever your code uses data, it should get that data from a model's getList() or getItem() method (depending on whether you need a single entity or a set of entities).
However, you'll want to manipulate exactly which data you'll be getting. In the case of a single item, you'll usually provide a unique key to the model.
$model = KService::get('com://admin/blog.model.posts) ->set( 'id', 1);
$post = model->getItem(); // returns the post with id=1
Note : In most cases you will use the primary key of the table but you can use any unique key defined in your table schema. For example :
$model = KService::get('com://admin/blog.model.posts) ->set( 'title', 'My first post');
$post = model->getItem(); // returns the post with title 'My first post'
Additional methods for getting list of items, getting items from non-database sources, ... can be found in KModel
States
In some cases you might need more states to manipulate or filter your data. For example, we only want to display posts that are from a certain publisher that have been published.
First, the model needs to be aware of those states. We do that by inserting the state in the model's state object:
$model->getState()
->insert('publisher', 'string')
->insert('published', 'int', 1);
- The first argument is the name of the state.
- The second argument is a filter for the type of value expected.
- The final argument is an optional default value.
Adding the model
The default admin list view we created before already showed a search input field and button but is missing some action. It is to the model to get the 'filtered' data and deliver it to the view.
So lets create the /components/models folder were all models will be stored.
Because the model will be part of the list view (plural) we need to create a file posts.php inside the models folder and put following code:
<?
class ComBlogModelPosts extends ComDefaultModelDefault
{
public function __construct(KConfig $config)
{
parent::__construct($config);
}
protected function _buildQueryWhere(KDatabaseQuery $query)
{
$state=$this->_state;
if($state->search) {
$query->where('title', '=', $state->search);
}
}
}
The class name, conform the naming convention, extends the ComDefaultModelDefault model allowing additional state parameters defined and build the query to filter the requested search data.