lundi 20 décembre 2021

Why are the methods declared in the interface not executed?

I'm trying to implement the Factory Method on the simplest basic example, but the log() methods in the FileLogger and StdoutLogger classes are simply skipped.

index.php

spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

function clientCode(LoggerFactory $creator)
{
   $creator->createLogger("hello");
}

clientCode(new FileLoggerFactory("uml\uml.txt"));
clientCode(new StdoutLoggerFactory("uml\uml.txt2"));

Logger.php

interface Logger
{
    public function log(string $message);
}

LoggerFactory.php

interface LoggerFactory
{
    public function createLogger(): Logger;
}

FileLoggerFactory.php

class FileLoggerFactory implements LoggerFactory
{
    private $filePath;

    public function __construct(string $filePath)
    {
      $this->filePath = $filePath;
    }

    public function createLogger(): Logger
    {
      return new FileLogger($this->filePath);
    }
}

StdoutLoggerFactory.php

class StdoutLoggerFactory implements LoggerFactory
{

    public function __construct()
    {

    }
    public function createLogger(): Logger
    {
        return new StdoutLogger();
    }
}

FileLogger.php

class FileLogger implements Logger
{
    private $filePath;

    public function __construct(string $filePath)
    {
      $this->filePath = $filePath;
    }

    public function log(string $message)
    {
        // the method does not work
        echo "message: $message </br>";
    }
}

StdoutLogger.php

class StdoutLogger implements Logger
{
    public function __construct()
    {

    }

    public function log(string $message)
    {
        // the method does not work
        echo "message: $message";
    }

}

Tell me how to correctly use the Factory Method pattern in this construction?

Aucun commentaire:

Enregistrer un commentaire