I was writing some code and I began to feel a little uncomfortable with messy parent::__construct calls and I was wondering firstly is it bad OOP practice and secondly is there a cleaner way to do it? See the particularly extreme example below that triggered my question.
<?php
class BrowseNodeLookupRequest extends Request {
protected $BrowseNodeId;
public function __construct($Service, $AWSAccessKeyID, $AssociateTag,
$Operation, $MerchantID = null, $ResponseGroup = null,
$Version = null, $Style = null, $ContentType = null,
$XMLEscaping = null, $Validate = null, $BrowseNodeId) {
parent::__construct($Service, $AWSAccessKeyID, $AssociateTag,
$Operation, $MerchantID, $ResponseGroup, $Version, $Style,
$ContentType, $XMLEscaping);
$this->setBrowseNodeId($BrowseNodeId);
}
protected function setBrowseNodeId($BrowseNodeId) {
if (is_string($BrowseNodeId)) {
$this->BrowseNodeId = $BrowseNodeId;
} else {
throw new Exception('BrowseNodeLookupRequest Parameter (BrowseNodeId
) Must be a String');
}
}
}
?>
With thanks to all the commenters, particularly Matthew, the solution I’ve gone with is to remove optional parameters from the constructor method of the parent class and add them to public setter methods available in the parent class. Revised code is below with usage example. Note that the ‘->setValidate’ and ‘->setResponseGroup’ are new methods inherited from the parent class. Obviously if you are in a similar situation but all of your parameters are required then you need to go for one of the other options outlined in the responses.
Revised Class:
Usage Example: