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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2462201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:34:16  来源:igfitidea点击:

Kohana 3: Example of model with validation

phpvalidationmodelkohana-3

提问by Svish

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?

谁能帮我举一个简单的例子来说明如何做到这一点?你会在哪里有模型中的规则?验证会在哪里进行?控制器如何知道验证是通过还是失败?控制器将如何获得错误消息之类的信息?

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

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

回答by preds

I too had difficulty finding examples for Kohana3, bestattendance's example is for Kohana2.

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

Here's an example I threw together in my own testing:

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

application / classes / model / news.php

应用程序/类/模型/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;
    }
}

application / messages / errors.php

应用程序/消息/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 / news.php

应用程序/类/控制器/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;
    }
}

application / views / news.php

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

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.

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

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.0.7 中进行了测试,应该可以为您提供如何布局代码的良好起点。与其他框架不同,Kohana 似乎对你把逻辑放在哪里是非常开放的,所以这对我来说是有意义的。如果你想使用 ORM 而不是滚动你自己的数据库交互,它有自己的验证语法,你可以在这里找到

回答by John Himmelman

An example of KO3 validation used with ORM models. Example was posted with permission by a1986 (blaa) in #kohana (freenode).

与 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;
  }
}

回答by bestattendance

Here's a simple example that works for me.

这是一个对我有用的简单示例。

In my model (client.php):

在我的模型(client.php)中:

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

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):

在我的控制器(clients.php)中:

<?php defined('SYSPATH') OR die('No direct access allowed.');

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 .= '<br />Performing Validation<br />';

        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 .= '<br />';
    print_r ($client->getFormValues());
    print_r ($client->getValidationErrors());


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

   }
?>

In my i18n file (form_errors.php):

在我的 i18n 文件 (form_errors.php) 中:

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

回答by Matt Toigo

I have a brief write up with how to handle this at the link below since it took me a while to figure out and I couldn't find a single good example.

我在下面的链接上写了一篇关于如何处理这个问题的简短文章,因为我花了一段时间才弄明白,而且我找不到一个好的例子。

http://www.matt-toigo.com/dev/orm_with_validation_in_kohana_3

http://www.matt-toigo.com/dev/orm_with_validation_in_kohana_3