Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of parameters

Tags:

php

cakephp

CakePHP makes heavy use of associative arrays for passing large numbers of parameters to functions. I have not really seen this technique outside of PHP and never seen it used to the extent that Cake uses it. I really like this approach because as it seems it would be easier to handle new parameters in future releases of your own code and it's alot more readable than simply a long list of params.

As an example...

function myFunc($params = array('name' => 'rob', 'count' => 5, 'anArray' => array('A string', 5, myObject)))
{
    // ...
}

I guess this is similar to using argc/argv, but is a bit easier to read. Does anyone have a list of pros and cons on this method or know of anyone that's written on best practices with this? I've tried just Googling it but "associative array of parameters" brings up pretty much every programming article ever written.

Also, is there even a term for passing parameters this way?

like image 642
rob5408 Avatar asked Feb 12 '26 16:02

rob5408


1 Answers

A downside to using named parameters is documenting the parameters with PHPDoc. Many editors/IDEs provide "automatic" documentation that can parse your code and generate generic docblocks.

e.g.

function foo(array $bar, SomeClass $stuff) { returns $magic; }

would produce:

/**
 * foo
 *
 * @param array $bar
 * @param SomeClass $stuff
 * @return mixed
 */
function foo(array $bar, SomeClass $stuff) { returns $magic; }

If you put all your parameters in a $params array, it would only look like

/**
 * foo
 *
 * @param array $params
 * @return mixed
 */

It also adds a lot of additional burden to your developers to have to type the extra code for each parameter. I'd suggest using a mix of the two approaches.

e.g. If you had a function to return an HTML text input element you could have the following method signature:

/**
 * formText
 *
 * @param string $name name of text element
 * @param string $value value of text element
 * @param array $options additional options for text element
 * @return string
 */
function formText($name, $value, $options = array());

Thus, you can easily pass the most common values to the function.

$this->formText('foo', 'Default...');

and if you need additional, less common params you'd use the convenient named parameter syntax:

$this->formText('foo', 'Default...', array(
    'class' => 'bold highlighted'
));

otherwise, using only a generic $params array you'd have to type:

$this->formText(array(
    'name' => 'foo',
    'value' => 'Default...'
));
like image 132
hobodave Avatar answered Feb 15 '26 05:02

hobodave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!