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/library/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();