我正在尝试扩展CodeIgniter表单验证库

时间:2013-03-06 21:27:15

标签: php codeigniter validation shared-libraries codeigniter-2

这是我的自定义验证功能。它使用a Google Maps CodeIgniter library中的地理编码来检查某个位置是否存在。

public function address_check($str)
{
    $this->load->library('GMap');
    $this->gmap->GoogleMapAPI();

    // this method checks the cache and returns the cached response if available
    $geocodes = $this->gmap->getGeoCode("{$str}, United States");

    $this->form_validation->set_message('address_check', 'The %s field contains an invalid address');

    if (empty($geocodes))
    {
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}

如果我将上面的函数与上面的规则一起放在我的控制器中,它可以很好地工作。

$this->load->library('form_validation');
$this->form_validation->set_rules('location', 'Location', 'callback_address_check');

现在我只想把它从我的控制器中移出。所以我正在尝试按照SO answerthe CI documentation扩展我的CodeIgniter表单验证库。

我在这里创建了一个文件:/codeigniter/application/libraries/MY_Form_validation.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {

    public function __construct()
    {
        parent::__construct();
    }

    public function address_check($str)
    {
        $this->load->library('GMap');
        $this->gmap->GoogleMapAPI();

        // this method checks the cache and returns the cached response if available
        $geocodes = $this->gmap->getGeoCode("{$str}, United States");

        $this->form_validation->set_message('address_check', 'The %s field contains an invalid address');

        if (empty($geocodes))
        {
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

}

从我的控制器中,我正在设置这样的规则......

$this->load->library('form_validation');
$this->form_validation->set_rules('location', 'Location', 'address_check');

我发现并解决了自己的第一个问题是没有发生任何事情,因为that SO answer错误地将文件名指定为My_Form_validation.php,它应该是MY_Form_validation.php

现在正在调用该函数,新问题是我收到以下错误:

  

消息:未定义属性:MY_Form_validation :: $ load

     

文件名:libraries / MY_Form_validation.php

     

行号:12

这是第12行:

$this->load->library('GMap');

我无法从库中访问库?解决这个问题的正确方法是什么?我不想自动加载GMap库,因为我不会一直使用它。我的方法中还有其他问题吗?

2 个答案:

答案 0 :(得分:5)

使用此:

$CI =& get_instance();
$CI->load->library('GMap');

然后使用它:

$CI->gmap->GoogleMapAPI();

你必须这样做,因为表单验证不像CI模型或Controller类,它只是库。

答案 1 :(得分:3)

在您的库中,您可以通过首先加载CI类来扩展其他模型,库,配置,帮助程序等。例如,在构造函数中,您可以通过以下方式完成此任务:

public function __construct()
{
    parent::__construct();

    $this->ci =& get_instance();
}

加载CI类后,您可以加载任何其他可能需要加载的类。

示例:

$this->ci->load->library("session");
$this->ci->load->model("my_model");
$this->ci->load->helper("file");

或者在你的情况下:

$this->ci->load->library("GMap");

然后,您可以在整个班级中以类似的方式调用班级中的函数:

$this->ci->gmap->GoogleMapAPI();
$this->ci->gmap->getGeoCode("{$str}, United States");