2015-12-23 32 views
0

我有以下列出的功能,目前在我的模型中調用 - > project_model.phpCodeIngniter 2.0 - 使一個功能可以訪問兩個模型?

我還需要在另一個名爲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; 
    }    
} 
+0

你可以做幾件事。我會建議只是把它變成一個「幫手」,以便於使用。請注意,爲了加載庫,您需要緩存對此處「CI」實例的引用。 '$ CI =&get_instance(); $ CI-> load-> library('GeoCoder');' – Ohgodwhy

+0

謝謝,那算得很好。我只是稍微改變了函數,以便它只返回數據數組,然後調用模型返回到數據庫。如果你改變你的評論到答案中,會高興地接受它。 – Nebri

回答

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(); 
相關問題