c# - Create CSV with columns selected by the user -
i have little design problem. let's have project contains large number of people. want allow user export people csv file information chooses.
example, choose id, name, phone number , according choice create file.
of course, there simple of way doing if(idcheckbox.checked) getid(); etc.
i'm looking better. don't want each new option add need change ui (e.g. new checkbox).
thought of reading possible options file, solved ui problem. how know values without using "if's" again?
you don't need fancy design pattern task. understand have identified reason change (added options in future). want minimize amount of classes modified.
your real problem how decouple csv creation objects structure going change. don't want parsing logic affected whenever person class changed.
in following example csv object decoupled objects receives , parses. achieve this, coding abstraction rather implementation. way not coupled person object, welcome objects implement attributedobject interface. dependency being injected our csv parser.
i implemented in php, idea same. c# static language, fetching attributes bit of change. might use kind of arrayaccess interface.
interface attributedobject { public function getattribute($attribute); } class person implements attributedobject { protected $firstname; protected $lastname; protected $age; protected $iq; public function __construct($firstname, $lastname, $age, $iq) { $this->firstname = $firstname; $this->lastname = $lastname; $this->age = $age; $this->iq = $iq; } public function getattribute($attribute) { if(property_exists($this, $attribute)) { return $this->$attribute; } throw new \exception("invalid attribute"); } } class csv { protected $attributedobject = null; protected $attributestodisplay = null; protected $csvrepresentation = null; protected $delimiter = null; public function __construct(attributedobject $attributedobject, array $attributestodisplay, $delimiter = '|') { $this->attributedobject = $attributedobject; $this->attributestodisplay = $attributestodisplay; $this->delimiter = $delimiter; $this->generatecsv(); } protected function generatecsv() { $tempcsv = null; foreach ($this->attributestodisplay $attribute) { $tempcsv[] = $this->attributedobject->getattribute($attribute); } $this->csvrepresentation = $tempcsv; } public function storecsv() { $file = fopen("tmp.csv", "w"); fputcsv($file, $this->csvrepresentation, $this->delimiter); } } $person1 = new person('john', 'doe', 30, 0); $csv = new csv($person1, array('firstname', 'age', 'iq')); $csv->storecsv();
Comments
Post a Comment