Skip to content

Commit

Permalink
Add per request in memory caching of country objects to improve perfo…
Browse files Browse the repository at this point in the history
…rmance
  • Loading branch information
DivineOmega committed May 13, 2020
1 parent 44adef1 commit 5d39f7c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
26 changes: 26 additions & 0 deletions src/Helpers/CountryHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php


namespace DivineOmega\LaravelAddresses\Helpers;


use DivineOmega\Countries\Countries;
use DivineOmega\Countries\Country;

abstract class CountryHelper
{
static $countriesByCode = [];

static function getByIsoCode($countryCode): ?Country
{
if (array_key_exists($countryCode, self::$countriesByCode)) {
return self::$countriesByCode[$countryCode];
}

$country = (new Countries())->getByIsoCode($countryCode);

self::$countriesByCode[$countryCode] = $country;

return $country;
}
}
3 changes: 2 additions & 1 deletion src/Models/Address.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use DivineOmega\LaravelAddresses\DistanceStrategies\Direct;
use DivineOmega\LaravelAddresses\Exceptions\InvalidCountryException;
use DivineOmega\LaravelAddresses\Exceptions\InvalidUKPostcodeException;
use DivineOmega\LaravelAddresses\Helpers\CountryHelper;
use DivineOmega\LaravelAddresses\Helpers\GoogleMaps;
use DivineOmega\LaravelAddresses\Interfaces\DistanceStrategyInterface;
use DivineOmega\LaravelAddresses\Objects\Location;
Expand Down Expand Up @@ -50,7 +51,7 @@ public function getCountryAttribute(): ?Country
return null;
}

return (new Countries())->getByIsoCode($this->country_code);
return CountryHelper::getByIsoCode($this->country_code);
}

public function getCountryNameAttribute(): ?string
Expand Down

0 comments on commit 5d39f7c

Please sign in to comment.