Kohana 3:带有验证的模型示例

2022-08-30 13:41:25

我找到了有关模型和验证的示例和教程。我把验证(或至少大部分)放在模型中,我同意这一点。但是我没有任何示例或教程来说明应该如何做到这一点。

任何人都可以帮我举一个简单的例子来说明如何做到这一点吗?模型中的规则在哪里?验证将在哪里进行?控制器如何知道验证是通过还是失败?控制器如何获取错误消息和类似的东西?

希望有人能帮忙,因为在这里感觉有点迷茫:p


答案 1

我也很难找到Kohana3的例子,bestattendance的例子是Kohana2。

以下是我在自己的测试中拼凑的一个例子:

应用 / 类 / 模型 / 新闻.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;
    }
}

应用程序 / 消息 / 错误.php

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

应用 / 类 / 控制器 / 新闻.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;
    }
}

应用 / 查看 / 新闻.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 ?>

若要使此代码在默认安装中正常工作,必须启用数据库模块并将其配置为身份验证。然后,您可以使用默认配置从索引.php/新闻访问它。

它在Kohana 3.0.7中进行了测试,应该会给你一个很好的起点,说明你如何布局代码。与其他框架不同,Kohana似乎非常开放,因为你把你的逻辑放在哪里,所以这对我来说是有意义的。如果要使用ORM而不是滚动自己的数据库交互,它有自己的验证语法,您可以在此处找到


答案 2

用于 ORM 模型的 KO3 验证示例。示例由 a1986 (blaa) 在 #kohana (freenode) 中发布。

<?php defined('SYSPATH') or die('No direct script access.');

class Model_Contract extends ORM {

  protected $_belongs_to = array('user' => array());

  protected $_rules = array(
    'document' => array(
      'Upload::valid'     => NULL,
      'Upload::not_empty' => NULL,
      'Upload::type'      => array(array('pdf', 'doc', 'odt')),
      'Upload::size'      => array('10M')
    )
  );

  protected $_ignored_columns = array('document');


  /**
   * Overwriting the ORM::save() method
   * 
   * Move the uploaded file and save it to the database in the case of success
   * A Log message will be writed if the Upload::save fails to move the uploaded file
   * 
   */
  public function save()
  {
    $user_id = Auth::instance()->get_user()->id;
    $file = Upload::save($this->document, NULL, 'upload/contracts/');

    if (FALSE !== $file)
    {
      $this->sent_on = date('Y-m-d H:i:s');
      $this->filename = $this->document['name'];
      $this->stored_filename = $file;
      $this->user_id = $user_id;
    } 
    else 
    {
      Kohana::$log->add('error', 'Não foi possível salvar o arquivo. A gravação da linha no banco de dados foi abortada.');
    }

    return parent::save();

  }

  /**
   * Overwriting the ORM::delete() method
   * 
   * Delete the database register if the file was deleted 
   * 
   * If not, record a Log message and return FALSE
   * 
   */
  public function delete($id = NULL)
  {

    if (unlink($this->stored_filename))
    {
      return parent::delete($id);
    }

    Kohana::$log->add('error', 'Não foi possível deletar o arquivo do sistema. O registro foi mantido no banco de dados.');
    return FALSE;
  }
}

推荐