Permalink
Browse files

重構 6 式 : Dependency Injection

  • Loading branch information...
1 parent 5f3b9ba commit 0ce3069cc50fe22d6e121aa00bb78183e10f14a4 Sam.IO.Hsiao committed Nov 27, 2016
Showing with 19 additions and 41 deletions.
  1. +3 −32 app/Services/ShippingService.php
  2. +16 −9 tests/ShippingServiceTest.php
@@ -7,42 +7,13 @@ class ShippingService
/**
* 計算運費
* @param array $weightArray
- * @param string $companyName
+ * @param LogisticsInterface $logistics
* @return int
*/
- public function calculateFee(array $weightArray, string $companyName): int
+ public function calculateFee(array $weightArray, LogisticsInterface $logistics) : int
{
$amount = 0;
- switch ($companyName) {
- case 'BlackCat':
- $logistics = new BlackCat();
- $amount = $logistics->calculateFee($weightArray, $amount);
-
- break;
- case 'Hsinchu':
- $logistics = new Hsinchu();
- $amount = $logistics->calculateFee($weightArray, $amount);
-
- break;
- case 'PostOffice':
- $logistics = new Post();
- $amount = $logistics->calculateFee($weightArray, $amount);
-
- break;
- default:
- $logistics = new BlackCat();
- $amount = $logistics->calculateFee($weightArray, $amount);
-
- break;
- }
-
- return $amount;
+ return $logistics->calculateFee($weightArray, $amount);
}
-
-
-
-
-
-
}
@@ -1,5 +1,9 @@
<?php
+use App\Services\BlackCat;
+use App\Services\Hsinchu;
+use App\Services\LogisticsInterface;
+use App\Services\Post;
use App\Services\ShippingService;
class ShippingServiceTest extends TestCase
@@ -8,12 +12,13 @@ class ShippingServiceTest extends TestCase
public function 黑貓_當重量為1_2_3_費用為360()
{
/** arrange */
- /** @var ShippingService $target */
- $target = App::make(ShippingService::class);
+ App::bind(LogisticsInterface::class, BlackCat::class);
/** act */
$weights = [1, 2, 3];
- $actual = $target->calculateFee($weights, 'BlackCat');
+ $actual = App::call(ShippingService::class . '@calculateFee', [
+ 'weightArray' => $weights
+ ]);
/** assert */
$expected = 360;
@@ -24,12 +29,13 @@ public function 黑貓_當重量為1_2_3時_費用為360()
public function 新竹_當重量為1_2_3_費用為330()
{
/** arrange */
- /** @var ShippingService $target */
- $target = App::make(ShippingService::class);
+ App::bind(LogisticsInterface::class, Hsinchu::class);
/** act */
$weights = [1, 2, 3];
- $actual = $target->calculateFee($weights, 'Hsinchu');
+ $actual = App::call(ShippingService::class . '@calculateFee', [
+ 'weightArray' => $weights
+ ]);
/** assert */
$expected = 330;
@@ -40,12 +46,13 @@ public function 新竹_當重量為1_2_3時_費用為330()
public function 郵局_當重量為1_2_3_費用為300()
{
/** arrange */
- /** @var ShippingService $target */
- $target = App::make(ShippingService::class);
+ App::bind(LogisticsInterface::class, Post::class);
/** act */
$weights = [1, 2, 3];
- $actual = $target->calculateFee($weights, 'PostOffice');
+ $actual = App::call(ShippingService::class . '@calculateFee', [
+ 'weightArray' => $weights
+ ]);
/** assert */
$expected = 300;

0 comments on commit 0ce3069

Please sign in to comment.