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.
finalclassFileLogger{private$logFilePath;protectedfunction__construct(string$logFilePath){$this->logFilePath=$logFilePath;}publicfunctionlog():void{$this->ensureLogFileExists();}}finalclassFileLoggerFactory{publicfunctioncreate(string$logFilePath):FileLogger{ensureLogFileExists($logFilePath);returnnewFileLogger($logFilePath);}privatefunctionensureLogFileExists(string$logFilePath):void{if(is_file($logFilePath)){return;}$logFileDirectory=dirname($logFilePath);if(!is_dir($logFileDirectory)){// create the directory if it doesn't exist yetmkdir($logFileDirectory,0777,true);}touch($logFilePath);}}
Also, I am new here and I have no idea how to have syntax highlight :(
Can you show your proposed solution in code? I mean that of the second method, bootstrapping.
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.
Also, I am new here and I have no idea how to have syntax highlight :(
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