Mainly the if getErrors() == true…
For me it’s easy to read but it’s sometimes irritating to type. Is this considered code re-use and abuse?
Any suggestions on how to trim it down if I should?
(I’m going to initialize the File inside the form object at some point, but that’s not what I’m asking yet)
function createSave()
{
$file = new File_Handler('file', false);
$file->setType = 'zip|gz|tar|rar';
$file->setLocation('../../../');
$file->save();
if ($file->getErrors() == false)
{
$this->form->post('assign_package');
$this->form->post('title|length=1,100');
$this->form->post('decription');
$this->form->setData('created', DATE_TIME);
$this->form->setData('physical_file', 'UNSURE YET');
if ($this->form->getErrors == false)
{
$this->db->insert('files', $this->form->getData());
if ($this->db->getErrors() == false)
$this->status('Results saved!');
else
$this->status($this->db->getErrors());
}
else
$this->status($this->form->getErrors());
}
else
$this->status($file->getErrors());
refresh('files');
}
Yes, it begins to look pretty messy as the conditional statements nesting goes many levels deep. I know what you mean, this happened to me many times, especially when validating a lot of data, and all I remember is that the code was becoming hard to read, maintain and modify later on. Then I began using exceptions for this and things got much better. Try this:
Then you can add as many points to catch errors as you wish without risking to make your code messy. Simply replace saving errors in your object property with throw Exception syntax and that’s it, the getErrors() method will not be necessary. You may want to use your own exception class if the built-in one is not enough.
Update: I realize that you may want to catch more than one error at a time and my previous example will not allow this. In such cases I collect errors somewhere in an object property (similar to what you were doing) and then use validate() method to throw the exception:
You would need to use your own exception class if you wanted to pass error messages as arrays because the standard one will not accept array parameters. Or use a workaround with delimiting error messages with some character. Personally, I would not do $db->validate(); because on db errors I almost always want to throw a very critical error and handle it in a special way (halt the application, show some generic alert to the user, log the exact error to a file, etc.).
Also if you don’t want to go with Exception and keep checking for errors, why don’t
replace the:
if ($this->db->getErrors() == false)
with
if (!$this->db->getErrors() )