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
358
363
{
359
-
$delivery = new $deliveryMethod;
360
-
$delivery->costLabel = 'Delivery cost is: ';
361
-
364
+
switch ($deliveryMethod) {
365
+
case 'dhl':
366
+
$delivery = new DHL;
367
+
break;
368
+
case 'ups':
369
+
$delivery = new UPS;
370
+
break;
371
+
default:
372
+
throw new \InvalidArgumentException('Unknown delivery method given');
373
+
}
374
+
375
+
// Since DeliveryFactory is a factory of DHL and UPS instances,
376
+
// priceLabel property with exactly this value ('Delivery price is: ')
377
+
// is accessible for them - you will see it soon.
378
+
$delivery->priceLabel = 'Delivery price is: ';
379
+
362
380
return $delivery;
363
381
}
364
-
365
-
abstract public function price();
382
+
366
383
}
367
384
368
-
As you can see, ``DeliveryFactory`` doesn't specify the exact class of the object that will be created.
369
-
370
385
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``)!
371
386
372
387
.. configuration-block::
@@ -378,11 +393,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::
448
+
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::
434
449
435
-
/**
436
-
* @Route("/get-deliveries-cost", methods={"GET"})
437
-
*/
438
450
public function getDeliveriesCost(DHL $dhl, UPS $ups)
439
451
{
440
452
// ...
441
453
442
-
// $dhl->costLabel and $ups->costLabel are fulfilled in factory method.
443
-
$dhlCost = $dhl->costLabel . $dhl->cost();
444
-
$upsCost = $ups->costLabel . $ups->cost();
454
+
// $dpd->priceLabel and $ups->priceLabel are fulfilled in factory method.
0 commit comments