DEV Community

Discussion on: Basics of Object Design - Part One

Collapse
olivermensahdev profile image
Oliver Mensah Author

Can you show your proposed solution in code? I mean that of the second method, bootstrapping.

Collapse
bajzathd profile image
Bajzáth Dávid • Edited

I wrote PHP code years ago, but I forgot it does not have nested classes like Java, that is what I was referencing with "make the FileLogger constructor only visible to that class", but you can do a similar thing if you make the constructor protected and move the Factory class to the same package.

final class FileLogger{
    private $logFilePath;
    protected function __construct(string $logFilePath){
        $this->logFilePath = $logFilePath;
    }
    public function log(): void{
        $this->ensureLogFileExists();
    }

}

final class FileLoggerFactory {

    public function create(string $logFilePath): FileLogger {
        ensureLogFileExists($logFilePath);
        return new FileLogger($logFilePath);
    }

    private function ensureLogFileExists(string $logFilePath): void{
        if (is_file($logFilePath)) {
            return;
        }
        $logFileDirectory = dirname($logFilePath);
        if (!is_dir($logFileDirectory)) {
            // create the directory if it doesn't exist yet
            mkdir($logFileDirectory, 0777, true);
        }
        touch($logFilePath);
    }
}

Also, I am new here and I have no idea how to have syntax highlight :(

Thread Thread
olivermensahdev profile image
Oliver Mensah Author • Edited

I have seen the approach as well. Thanks. So allowing the Factory object to new up the object.

For the code highlighting, you can use
3start-backticts
langauge(php, js, py, etc)

3end-backticks