CodeIgniter 2.0 - 使两个模型可以访问一个函数?

CodeIgniter 2.0 - Making a function accessible to two models?

我有下面列出的函数,目前在我的模型中调用 -> project_model.php

我还需要在另一个名为 product_model.php 的模型中使用此功能。

有没有一种简单的方法/位置可以放置此函数,以便它可用于两个模型,而无需在两个模型之间复制此函数?

这个项目目前是用 CodeIgniter 2.02 编写的

function get_geo_code($postal) {
    $this->load->library('GeoCoder');
    $geoCoder = new GeoCoder();

    $options['postal'] = $postal;        
    $geoResults = $geoCoder->GeoCode($options);                              

    // if the error is empty, then no error!
    if (empty($geoResults['error'])) {
        // insert new postal code record into database here.

        // massage the country code's to match what database wants.
        switch ($geoResults['response']->country)
        {
            case 'US':
                $geoResults['response']->country = 'USA';
                break;

            case 'CA':
                $geoResults['response']->country = 'CAN';
                break;
        }                       

        $data = array (
            'CountryName' => (string)$geoResults['response']->country,
            'PostalCode' => $postal,
            'PostalType' => '',
            'CityName' => (string)$geoResults['response']->standard->city,
            'CityType' => '',
            'CountyName' => (string)$geoResults['response']->country,
            'CountyFIPS' => '',
            'ProvinceName' => '',
            'ProvinceAbbr' => (string)$geoResults['response']->standard->prov,
            'StateFIPS' => '',
            'MSACode' => '',
            'AreaCode' => (string)$geoResults['response']->AreaCode,
            'TimeZone' => (string)$geoResults['response']->TimeZone,
            'UTC' => '',
            'DST' => '',
            'Latitude' => $geoResults['lat'],
            'Longitude' => $geoResults['long'],
        );                                              

        $this->db->insert('postal_zips', $data);            
        return $data;

    } else {                                    
        return null;
    }               
}

您可以创建一个助手或库来容纳该函数。因此,例如,在 CI 文件结构中创建文件:

/application/libraries/my_library.php

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

class My_library {

    public $CI; // Hold our CodeIgniter Instance in case we need to access it

    /**
    * Construct Function sets up a public variable to hold our CI instance
    */
    public function __construct() {
        $this->CI = &get_instance();
    }

    public function myFunction() {
        // Run my function code here, load a view, for instance
        $data = array('some_info' => 'for_my_view');
        return $this->CI->load->view('some-view-file', $data, true);
    }

}

现在,在您的模型中,您可以像这样加载库并调用您的函数:

$this->load->library('my_library');
$my_view_html = $this->my_library->myFunction();