首先,在中设置自定义验证规则libraries/MY_Form_validation.php
如果该文件不存在,请创建它。
内容MY_Form_validation.php
:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
function __construct($config = array())
{
parent::__construct($config);
}
function valid_num_products()
{
//Perhaps it would be better to store a maxProducts column in your users table. That way, every user can have a different max products? (just a thought). For now, let's be static.
$maxProducts = 3;
//The $this object is not available in libraries, you must request an instance of CI then, $this will be known as $CI...Yes the ampersand is correct, you want it by reference because it's huge.
$CI =& get_instance();
//Assumptions: You have stored logged in user details in the global data array & You have installed DataMapper + Set up your Product and User models.
$p = new Product();
$count = $p->where('user_id', $CI->data['user']['id'])->count();
if($count>=$maxProducts) return false;
else return true;
}
}
接下来,在 中设置您的规则config/form_validation.php
。
form_validation.php 的内容
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config = array
(
'addProduct' => array
(
array
(
'field' => 'name',
'label' => 'Product Name',
'rules' => 'required|valid_num_products'
)
)
);
接下来,在 中设置错误消息language/english/form_validation_lang.php
。添加以下行:
$lang['valid_num_products'] = "Sorry, you have exceeded your maximum number of allowable products.";
现在在控制器中,您将需要以下内容:
class Products extends MY_In_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
}
function add()
{
$p = $this->input->post();
//was there even a post to the server?
if($p){
//yes there was a post to the server. run form validation.
if($this->form_validation->run('addProduct')){
//it's safe to add. grab the user, create the product and save the relationship.
$u = new User($this->data['user']['id']);
$x = new Product();
$x->name = $p['name'];
$x->save($u);
}
else{
//there was an error. should print the error message we wrote above.
echo validation_errors();
}
}
}
}
最后,你可能想知道为什么我继承自MY_In_Controller
. Phil Sturgeon 在他的博客上写了一篇出色的文章,题为Keeping It Dry。在帖子中,他解释了如何编写从访问控制控制器继承的控制器。MY_In_Controller
通过使用这种范例,可以假定继承自的控制器已登录,$this->data['user']['id']
因此假定这些东西是可用的。其实$this->data['user']['id']
就是 SET 在MY_In_Controller
. 这可以帮助您以这样一种方式分离您的逻辑,即您不会在控制器的构造函数中检查登录状态,或者(甚至更糟)在它们的功能中。