Php Kohana 3:具有验证的模型示例
我找到了关于模型和验证的示例和教程。我认为验证(或至少大部分验证)应该在模型中,我同意这一点。但我无法找到任何示例或教程来说明应该如何做到这一点 有谁能帮我举一个简单的例子说明如何做到这一点?模型中的规则在哪里?验证将在哪里进行?控制器如何知道验证是通过还是失败?控制器如何获得错误消息和类似的东西Php Kohana 3:具有验证的模型示例,php,validation,model,kohana-3,Php,Validation,Model,Kohana 3,我找到了关于模型和验证的示例和教程。我认为验证(或至少大部分验证)应该在模型中,我同意这一点。但我无法找到任何示例或教程来说明应该如何做到这一点 有谁能帮我举一个简单的例子说明如何做到这一点?模型中的规则在哪里?验证将在哪里进行?控制器如何知道验证是通过还是失败?控制器如何获得错误消息和类似的东西 希望有人能帮助我,因为我在这里感到有点迷茫:p这里有一个简单的例子对我很有用 在我的模型(client.php)中: 我也很难找到Kohana3的例子,BestAttention的例子就是Kohana
希望有人能帮助我,因为我在这里感到有点迷茫:p这里有一个简单的例子对我很有用 在我的模型(client.php)中:
我也很难找到Kohana3的例子,BestAttention的例子就是Kohana2 下面是我在自己的测试中收集的一个示例: application/classes/model/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;
}
}
<?php
return array(
'title' => array(
'not_empty' => 'Title can\'t be blank.',
),
'post' => array(
'not_empty' => 'Post can\'t be blank.',
),
);
<?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 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 ?>
与ORM模型一起使用的KO3验证示例。该示例经a1986(blaa)许可发布在#kohana(freenode)
我在下面的链接中简要介绍了如何处理这个问题,因为我花了一段时间才弄明白,我找不到一个好的例子
回复!难以置信的非常感谢。我会仔细看一下,看看我是否能从中得到一些东西:)@Svish请接受答案,如果它对你有帮助的话。我觉得很有趣的是,SO有比项目本身更好的kohana 3文档。感谢您的精彩提问。实际上,代码的文档记录得非常好,并且与userguide模块的API部分结合在一起,我认为这非常好。但可能会有更多的例子,特别是在用户指南部分。还有很多待办事项和缺少的部分:)您的代码不应该在视图中抛出关于不存在的通知吗$validator['title']
?@zerkms$validator['title']在视图中作为验证失败时的默认文本。如果未设置,则输入将没有意义的默认值。变量是在bind('validator',$validator)中定义的,因此没有引用未定义变量的危险。是的,在null上进行键查找,但我不认为这是一个问题,除非您运行的是E_STRICT。“没有引用未定义变量的危险”-有注意未定义索引的危险XI不会提供指向404页面的链接。
<?php
return array(
'title' => array(
'not_empty' => 'Title can\'t be blank.',
),
'post' => array(
'not_empty' => 'Post can\'t be blank.',
),
);
<?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 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 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;
}
}