Answer the question
In order to leave comments, you need to log in
How to make a factory with parameters?
Good morning.
There is a need to make a class for exporting tabular data from the application: the type and data are given as input, and the finished file is output. In code I see it like this:
<?php
class DataExporter {
public function Create( $type ) {
$class = $type . 'Exporter';
return new $class;
}
}
class AbstractExporter {
public function setData( $data ) { ... }
public function getResult( ) { ... }
}
class CSVExporter extends AbstractExporter { ... }
class XLSXExporter extends AbstractExporter { ... }
<?php
$data = db::query( 'select * from table' );
$format = $request->get[ 'format' ];
$exporter = DataExporter::Create( $format );
$exporter->setData( $data );
echo $exporter->getResult( );
<?php
class XLSXExporter extends AbstractExporter {
public function setColumnWidth( $column, $width ) { ... }
public function setColumnStyle( $column, $style ) { ... }
}
<?php
$exporter = DataExporter::Create( $format );
$exporter->setData( $data );
if( $format == 'XLSX' ) {
$exporter->setColumnWidth( 0, 100 );
$exporter->setColumnWidth( 1, 30 );
$exporter->setColumnWidth( 2, 60 );
}
echo $exporter->getResult( );
Answer the question
In order to leave comments, you need to log in
I think not much was not implemented well, so if:
$driver = new XLSXExporter();
$exporter = new DataExporter($driver);
echo $exporter->getResult();
class DataExporter{
protected $driver;
function __construct(DriverExporterInterface $driver){
$this->driver = $driver;
}
function getResult(){
return $this->driver->process();
}
}
interface DriverExporterInterface{
public function process();
}
if( $format == 'XLSX' ) {
$driver = new XLSXExporter();
$driver->setColumnWidth( 0, 100 );
$driver->setColumnWidth( 1, 30 );
$driver->setColumnWidth( 2, 60 );
}
else{
$driver = new EmptyExporter();
}
$exporter = new DataExporter($driver);
$exporter->setData( $data );
echo $exporter->getResult();
To solve this problem, it is worth using not a factory, but a DI container
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question