I have the following function listed below, and is currently called in my model -> project_model.php
I'm also going to need to have this function available in another model called product_model.php.
Is there a simple way / place that I can put this function so that it is available to both models without the need to duplicate this function across both models?
this project is currently written in 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;
}
}
You could create a helper or library to house the function. So, for instance, in the CI file structure create the file:
/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);
}
}
Now, in your models, you can load the library and call your function like so:
$this->load->library('my_library');
$my_view_html = $this->my_library->myFunction();