Reputation: 14260
I am coding a php script that extracts data from json files and maps/saves it to appropriate structures in a DB. There will be several slight variations based on the content of the file. Now I was wondering which option is best suited for the code.
Assumptions: The code is not used as a component in other code The classes are not instantiated, but rather just a collection of static methods.
- Put all methods in a single class:
class Extractor {
public static function readFile() { }
public static function saveToDB() { }
public static function mapResumeData() { }
public static function mapEducationData() { }
}
- Have a baseclass Extractor and individual Childclasses based on what to extract:
class Extractor {
public static function readFile() { ... }
public static function saveToDB() { ... }
}
class ResumeExtractor extends Extractor {
public static function mapData() { ... }
}
class EductionExtractor extends Extractor {
public static function mapData() { ... }
}
- Use an interface as well (should I always do this? Best practice?):
interface IExtractor {
public static function readFile();
public static function saveToDB();
public static function mapData();
}
class Extractor {
public static function readFile() { ... }
public static function saveToDB() { ... }
}
class ResumeExtractor extends Extractor implements IExtractor {
public static function mapData() { ... }
}
class EductionExtractor extends Extractor implements IExtractor {
public static function mapData() { ... }
}
- Don't use classes and just put all functions in a namespace
use namespace Extractor;
function readFile();
function saveToDB();
function mapData();
- use traits
Upvotes: 1
Views: 34
Reputation: 317207
Without knowing how slight the "slight variations" are, it's somewhat difficult to suggest one approach over the other. However, your code apparently involves file reading, mapping and databases. Some people would split these things into dedicated Readers, DataMappers and a DBAL layer using stateful objects instead of static classes.
My recommendation would be to just make it work for your case somehow, e.g. write the code for one case and then duplicate or branch for the variations. Then check whether it makes sense to extract an abstraction and how. Coming up with a good abstraction first is not easy. And it's usually more expensive to change the abstraction when you figured out it's not how you needed it to be.
Use an interface as well (should I always do this? Best practice?):
The general recommendation is to program towards an interface. One benefit would be if you are using type hints, it gets easier to swap out concrete implementations in consuming code. However, if you don't have multiple implementations, there is no need for an interface. I usually defer creating an interface until I happen to need the second thing. If both of these things share some code, I create an abstract type instead.
Upvotes: 1