lundi 13 juin 2016

php design pattern for nealy similar json response

I´d like to write a small class in php which gets lat and long values from different GEO-APIs (like google maps or osm nominatim). Both provider return similar results as json but with different keys.

In getCordinates() you see the parsing for googles api. My question now is - is there a nice design pattern that I do not have to spoil the method with several if statements for every new geo provider and blow up the method but keep things separated?

public $googleEndPoint = "http://ift.tt/Rb1IdI";
public $OSMendPoint =  "http://ift.tt/1sHsUUV";
public $endpoint;
public $address;


function __construct($endpoint = 'google'){
    switch ($endpoint){
        case 'OSM':
            $this->endpoint = $this->OSMendPoint;
            break;
        default:
            $this->endpoint = $this->googleEndPoint;
        break; 
    }
}


function request(){
    $address = urlencode($this->address);
    $result = file_get_contents($this->endpoint.$address); 
    $response = json_decode($result, true);
    return $response;
}


function getCoordinates($address) {
    $this->address = $address;
    $response = $this->request();
    // this is google specific and does not fit for other provider
    if( $response['status']=='OK' ){
        $data_arr['lat'] = $response['results'][0]['geometry']['location']['lat']; 
        $data_arr['lon'] = $response['results'][0]['geometry']['location']['lng'];  
        $data_arr['formatted_address'] = $response['results'][0]['formatted_address'];   
            return $data_arr;            
        } else {
            return false;
        }
    }

Aucun commentaire:

Enregistrer un commentaire