When writing a CRUD MVC application, would you suggest using arrays instead of long (even short) parameter lists when writing an api for your business layer (model)?
For instance, which would you suggest:
1
// Posts::getPosts(20, 0, $category, 'date_added');
static function getPosts($limit = NULL, $offset = NULL, Model_Category $category = NULL, $sort_by = NULL);
2
// Posts::getPosts(array('limit' => 20, 'offset' => 0, 'category' => $category, 'sort_by' => 'date_added'));
static function getPosts(array $options = NULL);`
1 seems a lot cleaner and less prone to bugs, but 2 seems WAY more flexible (can easily add/switch parameters without changing the api). Just looking for reasons to go either way.
Thanks
I go with this rule of thumb:
If
and/or
Then it is probably a good idea to use an array to simulate keyword arguments. Otherwise, just go with standard arguments.
Also, consider using a parameter object to do complicated method calls.
EDIT: What would I do with this?
Well, with a parameter array (also known as keyword arguments in languages that support them, like Python), my personal preference would be to do this:
This gives you a few benefits:
$optionsis completely optional. Any required arguments should be arguments.extract()makes key-value pairs into variable-value pairs, so the rest of the method is completely oblivious to the fact you’re using a parameter array and not normal arguments.