You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
public static function create(string $deliveryMethod): DeliveryInterface
350
355
{
351
-
$delivery = new $deliveryMethod;
352
-
$delivery->costLabel = 'Delivery cost is: ';
353
-
356
+
switch ($deliveryMethod) {
357
+
case 'dhl':
358
+
$delivery = new DHL;
359
+
break;
360
+
case 'ups':
361
+
$delivery = new UPS;
362
+
break;
363
+
default:
364
+
throw new \InvalidArgumentException('Unknown delivery method given');
365
+
}
366
+
367
+
// Since DeliveryFactory is a factory of DHL and UPS instances,
368
+
// priceLabel property with exactly this value ('Delivery price is: ')
369
+
// is accessible for them - you will see it soon.
370
+
$delivery->priceLabel = 'Delivery price is: ';
371
+
354
372
return $delivery;
355
373
}
356
-
357
-
abstract public function price();
374
+
358
375
}
359
376
360
-
As you can see, ``DeliveryFactory`` doesn't specify the exact class of the object that will be created.
361
-
362
377
Next, use settings similar to those in the sections above. These settings allow you to define a factory method for subclasses without explicitly extending the abstract class (i.e., without ``class DHL extends DeliveryFactory``)!
363
378
364
379
.. configuration-block::
@@ -370,11 +385,11 @@ Next, use settings similar to those in the sections above. These settings allow
Now we can use our services as usual (via dependency injection). The only difference is that subclasses instances of services are created in the factory. Let's get those services in controller::
440
+
Now we can use our delivery services as usual (via dependency injection). The only difference is that subclasses instances of services are created in the factory. Let's get those services in controller::
426
441
427
-
/**
428
-
* @Route("/get-deliveries-cost", methods={"GET"})
429
-
*/
430
442
public function getDeliveriesCost(DHL $dhl, UPS $ups)
431
443
{
432
444
// ...
433
445
434
-
// $dhl->costLabel and $ups->costLabel are fulfilled in factory method.
435
-
$dhlCost = $dhl->costLabel . $dhl->cost();
436
-
$upsCost = $ups->costLabel . $ups->cost();
446
+
// $dpd->priceLabel and $ups->priceLabel are fulfilled in factory method.
0 commit comments