我找到關於模型和驗證的示例和教程。我說的驗證(或者至少大部分)應該在模型中,我同意這一點。但我不能有任何示例或教程來說明應該如何完成。Kohana 3:驗證模型示例
任何人都可以幫助我一個簡單的例子,說明如何做到這一點?你在模型中的規則在哪裏?驗證會在哪裏發生?控制器如何知道驗證是否通過?控制器如何獲得錯誤消息和類似的東西?
希望有人能幫助,原因覺得這裏有點失落:對
我找到關於模型和驗證的示例和教程。我說的驗證(或者至少大部分)應該在模型中,我同意這一點。但我不能有任何示例或教程來說明應該如何完成。Kohana 3:驗證模型示例
任何人都可以幫助我一個簡單的例子,說明如何做到這一點?你在模型中的規則在哪裏?驗證會在哪裏發生?控制器如何知道驗證是否通過?控制器如何獲得錯誤消息和類似的東西?
希望有人能幫助,原因覺得這裏有點失落:對
我也很難找到Kohana3的例子,bestattendance的例子是Kohana2。
這是我在我自己的測試一起扔了一個例子:
應用程序/類/模型/ 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.',
),
);
application/classes/controller/n ews.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訪問它。
它在Kohana 3.0.7中進行了測試,並且應該給你一個很好的開始你如何佈置代碼的方法。與其他框架不同的是,Kohana似乎對你放置邏輯的位置非常開放,所以這對我來說纔是有意義的。如果要使用ORM而不是滾動自己的數據庫交互,它有自己的驗證語法,您可以查找here
你的代碼不應該在View中拋出關於不存在'$ validator ['title']'的通知嗎? – zerkms 2012-02-16 01:11:34
如果驗證失敗,@zerkms $ validator ['title']在視圖中作爲的默認文本。如果沒有設置,則輸入的默認值是沒有意義的。該變量在bind('validator',$ validator)中定義,因此不存在對未定義變量的引用的危險。是的,一個關鍵的查找是在一個null上完成的,但是我不認爲這是一個問題,除非你正在運行E_STRICT。 – preds 2012-02-21 07:07:32
「沒有引用未定義變量的危險」---存在未定義索引通知的危險 – zerkms 2012-02-21 07:13:54
下面是對我工作的一個簡單的例子。
在我的模型(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'));
}
}
?>
在我的控制器(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);
}
}
?>
在我的i18n文件(form_errors.php):
$lang = Array (
'clientName' => Array (
'required' => 'The Client Name field is required.'
)
);
與ORM模型一起使用的KO3驗證示例。例子在1986年(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;
}
}
我有一個簡短的寫了如何在下面,因爲我花了一段時間才能找出鏈接處理這個問題,我無法找到一個很好的例子。
http://www.matt-toigo.com/dev/orm_with_validation_in_kohana_3
我不會提供轉到404頁面的鏈接。 – 2016-06-30 22:49:45
我覺得很有趣,因此具有更好的Kohana 3文檔不是項目本身。感謝您的好Q. – Brenden 2011-12-01 18:20:29
嗯,實際上這些代碼的記錄非常好,並且與userguide模塊的API部分配對,我認爲它非常好。但可能是更多的例子,特別是在用戶指南部分。很多TODO和丟失的東西:) – Svish 2011-12-02 10:01:06