I find examples and tutorials about models and about validation. And I places that say the validation (or most of it at least) should be in the model, which I agree with. But I
I too had difficulty finding examples for Kohana3, bestattendance's example is for Kohana2.
Here's an example I threw together in my own testing:
application / classes / model / news.php
_db->query(Database::SELECT, $sql, FALSE)
->as_array();
}
public function validate_news($arr) {
return Validate::factory($arr)
->filter(TRUE, 'trim')
->rule('title', 'not_empty')
->rule('post', 'not_empty');
}
public function add_news($d) {
// Create a new user record in the database
$insert_id = DB::insert('news_example', array('title','post'))
->values(array($d['title'],$d['post']))
->execute();
return $insert_id;
}
}
application / messages / errors.php
array(
'not_empty' => 'Title can\'t be blank.',
),
'post' => array(
'not_empty' => 'Post can\'t be blank.',
),
);
application / classes / controller / news.php
bind('validator', $validator)
->bind('errors', $errors)
->bind('recent_posts', $recent_posts);
if (Request::$method == "POST") {
//added the arr::extract() method here to pull the keys that we want
//to stop the user from adding their own post data
$validator = $news->validate_news(arr::extract($_POST,array('title','post')));
if ($validator->check()) {
//validation passed, add to the db
$news->add_news($validator);
//clearing so it won't populate the form
$validator = null;
} else {
//validation failed, get errors
$errors = $validator->errors('errors');
}
}
$recent_posts = $news->get_latest_news();
$this->request->response = $view;
}
}
application / views / news.php
Errors:
To get this code working in a default install, you would have to enable the database module and configure it for authentication. Then you can access it from index.php/news using default configuration.
It is tested in Kohana 3.0.7 and should give you a good starting point of how you might lay out code. Unlike other frameworks, Kohana seems to be very open ended as to where you put your logic so this is just what made sense to me. If you want to use the ORM instead of rolling your own database interaction, it has its own syntax for validation which you can find here