Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
12 | trait HasGeoAbilities |
||
13 | { |
||
14 | public $geoEnabled = true; |
||
15 | |||
16 | public static function bootHasGeoAbilities() |
||
24 | |||
25 | public function registerGeoMacros() |
||
37 | |||
38 | public function addGeo($models) |
||
48 | |||
49 | public function removeGeo($models) |
||
59 | |||
60 | public static function geoImportAll() |
||
66 | |||
67 | public static function geoRemoveAll() |
||
73 | |||
74 | public function geoDistanceFrom($model) |
||
81 | |||
82 | public function scopeGeoNearest($builder, $radius = 10) |
||
83 | { |
||
84 | $locations = array_keys(Geo::index($this->geoIndex())->from($this->toCoordinate(), $radius)); |
||
85 | |||
86 | $builder->whereIn($this->geoKeyName(), $locations); |
||
87 | |||
88 | View Code Duplication | if ($this->databaseDriver() !== 'sqlite' && ! empty($locations)) { |
|
89 | $builder->orderByRaw(DB::raw(sprintf('FIELD(%s,%s)', $this->geoKeyName(), implode(',', $locations)))); |
||
90 | } |
||
91 | } |
||
92 | |||
93 | public function scopeGeoSearch($builder, $longitude, $latitude, $radius, $sort = 'ASC') |
||
94 | { |
||
95 | $locations = array_keys(Geo::index($this->geoIndex())->search($longitude, $latitude, $radius, $sort)); |
||
96 | |||
97 | $builder->whereIn($this->geoKeyName(), $locations); |
||
98 | |||
99 | View Code Duplication | if ($this->databaseDriver() !== 'sqlite' && ! empty($locations)) { |
|
100 | $builder->orderByRaw(DB::raw(sprintf('FIELD(%s,%s)', $this->geoKeyName(), implode(',', $locations)))); |
||
101 | } |
||
102 | } |
||
103 | |||
104 | public function getGeoUnitAttribute() |
||
108 | |||
109 | public function getGeoDistanceAttribute() |
||
117 | |||
118 | public function geoEnabled() |
||
122 | |||
123 | public function geoIndex() |
||
127 | |||
128 | public function geoKeyName() |
||
132 | |||
133 | public function geoKey() |
||
137 | |||
138 | public function geoLongitude() |
||
142 | |||
143 | public function geoLatitude() |
||
147 | |||
148 | public function toCoordinate() |
||
152 | |||
153 | public function toArray() |
||
164 | |||
165 | protected function databaseDriver() |
||
171 | } |
||
172 |
Let’s assume that you have a directory layout like this:
and let’s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: