StuffandBlah
StuffandBlah

Reputation: 1067

Where to validate inputs in PHP classes - best practice

I'm building a simple php app using OOP that creates a CSV file based on data from a DB.

I have a Config class which consists of a method named: open, which gets data from a ini file (ini filename passed in as parameter). This data is then mapped out to private fields and is accessed via accessors. I also have a save method, which I will use to write data back to the ini file.

Within my Utils class I have a static method: createCsv which creates the CSV. I pass to it data, delimiters & output file (passed from the config object).

My Question is this - Where should I validate the data?

At present I have conditional logic on the open method in the Config class to check to make sure that values are set correctly before I bind them to private member variables.

Should I also be putting conditional validation on my Utils::createCsv method as well?

Upvotes: 1

Views: 554

Answers (1)

Tadeck
Tadeck

Reputation: 137310

You should always put validation logic within model. And Config seems to be such model within your app.

Keep also in mind the rule of DRY (Dont-Repeat-Yourself), meaning you should avoid duplicating code.

Upvotes: 1

Related Questions