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

标签 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;
    }
}

如果我将上面的函数和下面的规则一起放在我的 Controller 中,它会工作得很好。

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

现在我只想将它从我的 Controller 中移出。所以我正在尝试根据这个 SO answer 扩展我的 CodeIgniter 表单验证库和 the CI documentation .

我在这里创建了一个文件:/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;
        }
    }

}

在我的 Controller 中,我正在设置这样的规则......

$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

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

Message: Undefined property: MY_Form_validation::$load

Filename: libraries/MY_Form_validation.php

Line Number: 12

这是第 12 行:

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

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

最佳答案

使用这个:

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

然后像这样使用它:

$CI->gmap->GoogleMapAPI();

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

关于php - 我正在尝试扩展 CodeIgniter 表单验证库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15258409/

相关文章:

JavaScript 表单验证 : understanding function call

java - 如果它是 Java 中的正确格式,如何验证字符串

php - 使用php自动创建缓存文件

如果记录不存在,php 不会返回消息 :"Record dont exist"

mysql - 如何在 View 文件上使用 NOT IN 查询

php - 您的 SQL 语法有误;检查与您的 MySQL 服务器版本对应的手册,了解在第 3 行 '' 附近使用的正确语法

php - 如何将波斯语/阿拉伯语数字从字符串转换为英语数字?

php - 从 MySQL 数据库填充 PHP 下拉列表

mysql - 外部连接没有给出预期的结果

HTML 验证程序 "self-closing syntax"和 "non-void"错误