Kohana 3:带有验证的模型示例 [英] Kohana 3: Example of model with validation

查看:48
本文介绍了Kohana 3:带有验证的模型示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到有关模型和验证的示例和教程.我认为验证(或至少其中的大部分)应该在模型中,对此我表示赞同.但是我无法显示任何示例或教程来说明应如何进行.

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 can't any examples or tutorials that show how that should be done.

有人可以通过一个简单的示例来帮助我吗?您在模型中的哪里有规则?验证将在哪里进行?控制器如何知道验证是通过还是失败?控制器如何获取错误消息之类的信息?

Could anyone help me with a simple example on how that could be done? Where would you have the rules in the model? Where would the validation happen? How would the controller know if the validation passed or fail? How would the controller get error messages and things like that?

希望有人可以帮助您,让您在这里有些失落:p

Hope someone can help, cause feel a bit lost here :p

推荐答案

我也很难找到Kohana3的示例,bestattendance的示例就是Kohana2.

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:

应用程序/类/模型/news.php

<?php defined('SYSPATH') OR die('No Direct Script Access');

Class Model_News extends Model
{
    /*
       CREATE TABLE `news_example` (
       `id` INT PRIMARY KEY AUTO_INCREMENT,
       `title` VARCHAR(30) NOT NULL,
       `post` TEXT NOT NULL);
     */

    public function get_latest_news() {
        $sql = 'SELECT * FROM `news_example` ORDER BY `id` DESC LIMIT  0, 10';
        return $this->_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;
    }
}

应用程序/消息/errors.php

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

应用程序/类/控制器/news.php

<?php defined('SYSPATH') OR die('No Direct Script Access');

Class Controller_News extends Controller
{
    public function action_index() {
        //setup the model and view
        $news = Model::factory('news');
        $view = View::factory('news')
            ->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;
    }
}

应用程序/视图/news.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 ?>

要使此代码在默认安装中运行,您必须启用数据库模块并将其配置为进行身份验证.然后,您可以使用默认配置从index.php/news访问它.

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.

它已在Kohana 3.0.7中进行了测试,应该为您提供如何布局代码的良好起点.与其他框架不同,Kohana对于您放置逻辑的位置似乎很开放,所以这对我来说才有意义.如果要使用ORM而不是滚动自己的数据库交互,则它具有自己的验证语法,您可以找到这里

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

这篇关于Kohana 3:带有验证的模型示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆