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

时间:2015-12-23 16:50:46

标签: php codeigniter-2

我有以下列出的功能,目前在我的模型中调用 - > project_model.php

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

是否有一个简单的方法/地方可以放置此功能,以便两个模型都可以使用它而无需在两个模型中复制此功能?

这个项目目前用CodeIngniter 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;
    }               
}

1 个答案:

答案 0 :(得分:1)

您可以创建一个帮助器或库来容纳该功能。因此,例如,在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();