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
Copy file name to clipboardExpand all lines: service_container/factories.rst
+133Lines changed: 133 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -301,5 +301,138 @@ previous examples takes the ``templating`` service as an argument:
301
301
->args([service('templating')])
302
302
;
303
303
};
304
+
305
+
Usage example
306
+
--------------------
307
+
308
+
The following example is intended to show how to create and use a factory method in Symfony framework.
309
+
Suppose you want to realize the factory method pattern for services, that describe two delivery methods - DPD and SmartPost.
310
+
311
+
Services (subclasses) definition::
312
+
313
+
// src/Deliveries/DPD.php
314
+
namespace App\Deliveries;
315
+
316
+
class DPD
317
+
{
318
+
public $costLabel;
319
+
320
+
public function cost() {
321
+
return 100;
322
+
}
323
+
}
324
+
325
+
// src/Deliveries/SmartPost.php
326
+
namespace App\Deliveries;
327
+
328
+
class SmartPost
329
+
{
330
+
public $costLabel;
331
+
332
+
public function cost() {
333
+
return 200;
334
+
}
335
+
}
336
+
337
+
Factory definition::
338
+
339
+
// src/Factories/DeliveryFactory.php
340
+
namespace App\Factories;
341
+
342
+
abstract class DeliveryFactory
343
+
{
344
+
public static function create($deliveryMethod)
345
+
{
346
+
$delivery = new $deliveryMethod;
347
+
$delivery->costLabel = 'Delivery cost is: ';
348
+
349
+
return $delivery;
350
+
}
351
+
352
+
abstract public function price();
353
+
}
354
+
355
+
As you can see, ``DeliveryFactory`` doesn't specify the exact class of the object that will be created.
356
+
357
+
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 DPD extends DeliveryFactory``)!
Now we can use our services as usual (via dependency injection). The only difference is that object instances are created in the factory. Let's get those services in controller::
423
+
424
+
/**
425
+
* @Route("/get-deliveries-cost", methods={"GET"})
426
+
*/
427
+
public function getDeliveriesCost(DPD $dpd, SmartPost $smartPost)
428
+
{
429
+
// ...
430
+
431
+
// $dpd->costLabel is fulfilled in factory method.
0 commit comments