samedi 7 mars 2020

Composite Pattern in a PHP example

I am currently looking into creating a simple functionality for exporting some data. Thing is that I'm a bit confused on whether my understanding of this pattern is correct, and whether my example represent a proper usage of the two.

I quickly wrote the code below, so it might have some mistakes.

Composite example

interface Exporter
{
    public function export(): void
}

class ProductExporter implements Exporter
{
    public function export(): void {}
}


class CategoryExporter implements Exporter
{
    public function export(): void {}
}

class ExporterComposite implements Exporter
{
    private $exporters = [];

    public function export()
    {
        foreach($this->exporters as $exporter) {
            $exporter->export();
        }
    }

    public function addExporter(Exporter $exporter)
    {
        $this->exporters[] = $exporter;
    }

}

The problem that I see here is that my "composite" attempt is problematic due to the fact that the ExporterComposite method addExporter() parameter could potentially accept its own class. This could be easily avoided with some custom code added in addExporter.

Aucun commentaire:

Enregistrer un commentaire