documentation - PHP: How to document array when they are method parameters -
what's best way document elements of array when parameter method? example, using phpdoc headers, might have like:
@param array $data
what doesn't tell me elements mandatory in array, , optional elements. imagine should go in explanation of method. like:
array: $data ============ int $id required name $string required town $string optional
if have such complex array constraints every single member, wouldn't use anonymous array rather defined object. array, can never sure holds, that's passing "object" in e.g. java, consider choice.
however, there possibility of little hinting, when array contains objects of type explained here, that's not answer question.
if need parameter array, might document way proposed in method's description; however, if use object parameter, you'd have additional support in modern ides (intellisense , on).
edit: mean, me question "why want use anonymous array instead of self defined type" - , besides simplicity (which backfire technical debt later if maintain , extend code), cannot think of reason, compared gain in using user defined type (self documented code, constraints visible , made explicit standard methods , on).
if need dump of data, might want go simple array, since you're thinking optional , required keys, screams user defined type.
edit2: regarding comment if have array source: i'm not sure whether need pass on array or "mapping" operations receive array (e.g. $_post or return value third party library or php internal functions or such).
i suppose 1 argue it's not model's business interpret data generated views (e.g. html forms post data), rather controller's resonsibility react accordingly input , transfer model in appropriate state. mean if receive e.g. array $_post:
$customer = new customer(); $customer->setid($_post['id']); $customer->setname($_post['name']); $customer->settown($_post['town']);
and handle errors access $customer, e.g. throwing exceptions if name not set (i.e. $_post['name']
empty or such). way, use source array call setters on object instead of e.g. passing array factory customer::buildbyhttppostdata(array $data)
, thereby delegating knowledge of view's details (names of html input tags , such).
bottom line is, there's no "standard" way declare required or optional array keys, , of course can describe constraints in method description, perhaps can circumvent keeping supported ways phpdoc comments on setters or getters.
of course, there may better ways approach problem, , perhaps comes better answer how handle it.
Comments
Post a Comment