Contents
  1. 1. Create a trait
  2. 2. Use a trait
  3. 3. Real implementation

Requirement PHP 5.4+

Create a trait

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
trait Geocodable {
/** @var string */
protected $address;
/** @var \Geocoder\Geocoder */
protected $geocoder;
/** @var \Geocoder\Result\Geocoded */
protected $geocoderResult;

public function setGeocoder(\Geocoder\GeocoderInterface $geocoder)
{
$this->geocoder = $geocoder;
}
public function setAddress($address)
{
$this->address = $address;
}
public function getLatitude()
{
if (isset($this->geocoderResult) === false) {
$this->geocodeAddress();
}
return $this->geocoderResult->getLatitude();
}
public function getLongitude()
{
if (isset($this->geocoderResult) === false) {
$this->geocodeAddress();
}
return $this->geocoderResult->getLongitude();
}
protected function geocodeAddress()
{
$this->geocoderResult = $this->geocoder->geocode($this->address);
return true;
}
}

Use a trait

1
2
3
4
5
6
<?php
class RetailStore
{
use Geocodable;
// Class implementation goes here
}

Real implementation

The PHP interpreter copies and pastes traits into class definitions at compile time, and it does not protect against incompatibilities introduced by this action. If your PHP trait assumes a class property or method exists (that is not defined in the trait itself), be sure those properties and methods exist in the appropriate classes.

1
2
3
4
5
6
7
8
9
10
<?php
$geocoderAdapter = new \Geocoder\HttpAdapter\CurlHttpAdapter();
$geocoderProvider = new \Geocoder\Provider\GoogleMapsProvider($geocoderAdapter);
$geocoder = new \Geocoder\Geocoder($geocoderProvider);
$store = new RetailStore();
$store->setAddress('420 9th Avenue, New York, NY 10001 USA');
$store->setGeocoder($geocoder);
$latitude = $store->getLatitude();
$longitude = $store->getLongitude();
echo $latitude, ':', $longitude;
Contents
  1. 1. Create a trait
  2. 2. Use a trait
  3. 3. Real implementation