开发者

How can I separate the callback logic in the one single file using codeigniter?

开发者 https://www.devze.com 2023-04-01 23:00 出处:网络
I use the config.php to store all the form_validation rules...But I would like to store the callback function in one single file too, how can I do so? Any ideas? Thank you....

I use the config.php to store all the form_validation rules...But I would like to store the callback function in one single file too, how can I do so? Any ideas? Thank you....

Now my file is something like this:

User_controller under user controller have many customized callback_valid , but I ready move all the rules in the config.php. I would like to put the _valid callback to one class.开发者_开发技巧 Thank you .


By default, the Form_validation lib uses it's $CI property to see if the callback method exists. Normally this looks at the current controller. However, you can change this behavior by extending the validation class and altering the run() method.

class MY_Form_validation extends CI_Form_validation {

    /**
     * Support for validation callbacks from any object
     * 
     * @access      public
     * @param       object      The object to run callbacks from
     * @param       string      Is there a validation rule for the particular URI being accessed?
     * @return      bool        Validation status
     */
    function run($obj = '', $group = '')
    { 
        // Assign the callback object
        if (is_object($obj)) $this->CI =& $obj;

        // Run the validation as normal
        return parent::run($group);
    }

}

We're just reassigning the $CI property. So to use callbacks from a class called user_validation for instance, you can do this:

$callback_class = $this->user_validation;
if ($this->form_validation->run($callback_class)) {}

Any loaded class will work, so you can store callback rules in models or libraries, just pass the object you want to handle callbacks with to the run() method.


What I would do in this case is just create a MY_Form_validation class to extend CodeIgniter's form validation. Place the "_valid" checks in the newly created MY_Form_Validation file and set the rules for the "_valid" checks the same way that you do for the default form_validation rules.

Something like...

class MY_Form_validation extends CI_Form_validation {

    function valid_user($str)
    {

    } 

    function valid_password($str)
    {

    }  
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消