1.3. Factory Method

    For simple cases, this abstract class could be just an interface.

    This pattern is a “real” Design Pattern because it achieves theDependency Inversion principle a.k.a the “D” in SOLID principles.

    It means the FactoryMethod class depends on abstractions, not concreteclasses. This is the real trick compared to SimpleFactory orStaticFactory.

    You can also find this code on GitHub

    Logger.php

    StdoutLogger.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Creational\FactoryMethod;
    4.  
    5. class StdoutLogger implements Logger
    6. {
    7. public function log(string $message)
    8. {
    9. echo $message;
    10. }

    LoggerFactory.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Creational\FactoryMethod;
    4.  
    5. interface LoggerFactory
    6. {
    7. public function createLogger(): Logger;
    8. }

    StdoutLoggerFactory.php

    FileLoggerFactory.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Creational\FactoryMethod;
    4.  
    5. class FileLoggerFactory implements LoggerFactory
    6. {
    7. * @var string
    8. */
    9. private $filePath;
    10.  
    11. public function __construct(string $filePath)
    12. {
    13. $this->filePath = $filePath;
    14. }
    15.  
    16. public function createLogger(): Logger
    17. {
    18. return new FileLogger($this->filePath);
    19. }
    20. }