[KOHANA] Bài 8 Kohana Model

Kohana Model

 

Models

 model quản lý những thao tác và dữ liệu của ứng dụng. Phản hồi những yêu cầu về trạng thái (thường sử dụng từ view) và phản hồi những lệnh thay đổi trạng thái thường từ controller

Cách tạo một model đơn giản :

class Model_Post extends Model
{
    public function do_stuff()
    {
        // This is where you do domain logic...
    }
}

If bạn một tạo những thao tác đến database, model  bạn viết sẽ phải kế thừa từ lớp Model_Database như sau:

class Model_Post extends Model_Database
{
    public function do_stuff()
    {
        // This is where you do domain logic...
    }
 
    public function get_stuff()
    {
        // Get stuff from the database:
        return $this->db->query(...);
    }
}

Sau đây là một ví dụ cho model như sau 

Với cơ sở dữ liệu được tạo từ bài trước http://hoaiphan.com/?q=forum/kohana-b%C3%A0i-7-tutorial-k%E1%BA%BFt-h%E1%BB%A3p-database-controller-template-view-validation

với CSDL  http://www.mediafire.com/?had5t7yhyyj7lry

 tạo tập tin application/classes/model/article.php

<?php defined('SYSPATH') OR die('No Direct Script Access');
Class Model_Article extends Model
{
    /* CREATE TABLE IF NOT EXISTS `article` ( `article_id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `content` text COLLATE utf8_unicode_ci NOT NULL, `post_userid` int(11) NOT NULL, `category` int(11) NOT NULL, `post_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`article_id`), KEY `article_id` (`article_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ;
     */

    public function get_latest_article() {
/*viet theo kieu thuong
        $sql
= 'SELECT * FROM `article` ORDER BY `article_id` DESC LIMIT  0, 10';         return DB::query(Database::SELECT, $sql)->execute()->as_array();/**/
// dung kieu dung săn Query Builder

return DB::select()->from('article')->limit(10)->order_by('article_id', 'DESC')->execute()->as_array(NULL);
     }     public function validate_article($arr) {         return Validation::factory($arr) //khong dung Validate nua            //  ->filter(TRUE, 'trim') khong dung tu version 3.1 troo len             ->rule('title', 'not_empty')             ->rule('post', 'not_empty');     }     public function add_article($d) {
        // Create a new user record in the database         $insert_id = DB::insert('article_example', array('title','post'))             ->values(array($d['title'],$d['post']))             ->execute();         return $insert_id;     } }




application / messages / errors.php

<?php return array(
    'title' => array(
        'not_empty' => 'Title can\'t be blank.',
    ),
    'post' => array(
        'not_empty' => 'Post can\'t be blank.',
    ),
);



application / classes / controller / article.php
<?php defined('SYSPATH') OR die('No Direct Script Access');
Class Controller_Article extends Controller
{
    public function action_index() {
        //setup the model and view
        $article = Model::factory('article');
        $view = View::factory('article')
            ->bind('validator', $validator)
            ->bind('errors', $errors)
            ->bind('recent_posts', $recent_posts);

        //  truoc version 3.x 
	  //if (Request::$method == "POST") {
if ($this->request->method() == HTTP_Request::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 = $article->validate_article(arr::extract($_POST,array('title','post')));
            if ($validator->check()) {
                //validation passed, add to the db
                $article->add_article($validator);
                //clearing so it won't populate the form
                $validator = null;
            } else {
                //validation failed, get errors
                $errors = $validator->errors('errors');
            }
        }
        $recent_posts = $article->get_latest_article();
        $this->response->body($view);
    }
}
application / views / article.php
<?php if ($errors): ?>
<p>Errors:</p>
<ul>
<?php foreach ($errors as $error): ?>
    <li><?php echo $error ?></li>
<?php endforeach ?>
</ul>
<?php endif ?>
<?php echo Form::open() ?>
<dl>
    <dt><?php echo Form::label('title', 'title') ?></dt>
    <dd><?php echo Form::input('title', $validator['title']) ?></dd>
    <dt><?php echo Form::label('post', 'post') ?></dt>
    <dd><?php echo Form::input('post', $validator['post']) ?></dd>
</dl>
<?php echo Form::submit(NULL, 'Post') ?>
<?php echo Form::close() ?>
<?php if ($recent_posts): ?>
<ul>
<?php foreach ($recent_posts as $post): ?>
    <li><?php echo $post['title'] . ' - ' . $post['post'];?></li>
<?php endforeach ?>
</ul>
<?php endif ?>

Here's a simple example that works for me.

In my model (client.php):

class Client_Model extends Model {

public $validation;

// This array is needed for validation
public $fields = array(
'clientName' => ''
);

public function __construct() {
// load database library into $this->db (can be omitted if not required)
parent::__construct();

$this->validation = new Validation($_POST);
$this->validation->pre_filter('trim','clientName');
$this->validation->add_rules('clientName','required');
}

public function create() {
return $this->validation->validate();
}

// This might go in base Model class
public function getFormValues() {
return arr::overwrite($this->fields, $this->validation->as_array());
}

// This might go in base Model class
public function getValidationErrors() {
return arr::overwrite($this->fields, $this->validation->errors('form_errors'));
}
}

?>
In my controller (clients.php):

class Clients_Controller extends Base_Controller {

public function __construct() {
parent::__construct();
}

public function index() {

$content = new View('clients/read');
$content->foobar = 'bob.';

$this->template->content = $content;
$this->template->render(TRUE);

}

/* A new user signs up for an account. */
public function signup() {

$content = new View('clients/create');
$post = $this->input->post();
$client = new Client_Model;

if (!empty($post) && $this->isPostRequest()) {
$content->message = 'You submitted the form, '.$this->input->post('clientName');
$content->message .= '
Performing Validation
';

if ($client->create()) {
// Validation passed
$content->message .= 'Validation passed';
} else {
// Validation failed
$content->message .= 'Validation failed';
}

} else {
$content->message = 'You did not submit the form.';
}

$contnet->message .= '
';
print_r ($client->getFormValues());
print_r ($client->getValidationErrors());

$this->template->content = $content;
$this->template->render(TRUE);
}

}
?>
In my i18n file (form_errors.php):

$lang = Array (
'clientName' => Array (
'required' => 'The Client Name field is required.'
)
);