1

I need an advice for my simple project. It's a logger system. I have the following files/classes

File - check if file exist is readable etc

ConfigParser - it's an abstract class of which I use the __construct method to do some things. The class is never instantiated directly. It's a decorator.

abstract class ConfigParser
{
    protected $filename;

    public function __construct($file)
    {
       // Here I want to invoke validate() method of File class
       // I know that I can do $file = new File(); $file->validate()
       // but the idea is to keep the things decoupled
       // Also I know that I can extend the File class ConfigParser extends File
       // but this doesn't make sence
       // I can pass the File object on child class new XmlParser('file.xml', $fileObj)
       // but this doesn't make sence too.
       // I don't want to use traits as it's bizarre for me

    }
}

XmlParser - extends ConfigParser

IniParser - extends ConfigParser

As the project goal is to keep the classes decoupled I can't figure out how to implement the File class in this scenario.

MZON
  • 305
  • 1
  • 3
  • 10

1 Answers1

0

I don't think it's such a nice design to do the validation in the constructor. A constructor should simply create the Parser and possibly do simple things.

What you could do would be using the template method pattern, then do the validation in the parent class and delegate the real parsing to the actual parser class.

abstract class ConfigParser {

  final function parse(){
     $file->validate();
     $this->conreteParse();
  }

  abstract function concreteParse();
}
rethab
  • 7,170
  • 29
  • 46