I have bunch of methods in which i need to test whether remote server has been reached or not and if not, reach it.
My first idea was __call magic method, but the method is called only when real method (with the original name) is not presented.
<?php
public function __call( $name, $arguments ) {
$needsExecution = array(
'getBody', 'getHeader', 'getHeaders', 'getRawOutput',
'getStatusCode', 'getFullHttp'
);
if ( in_array( $name, $needsExecution ) ) {
if ( !$this->hasBeenExecuted() ) {
$this->execute();
}
}
}
public function getBody() {
return $this->responseBody;
}
public function getHeaders() {
return $this->responseHeaders;
}
?>
Do I really need to have bunch of if's in each method or there's a way how to do that better?
What about changing up your code like this:
<?php
public function __call( $name, $arguments ) {
$needsExecution = array(
'getBody', 'getHeader', 'getHeaders', 'getRawOutput',
'getStatusCode', 'getFullHttp'
);
if ( in_array( $name, $needsExecution ) ) {
if ( !$this->hasBeenExecuted() ) {
$this->execute();
}
return $this->{'_' . $name}();
//return call_user_func(array($this, '_' . $name));
}
}
protected function _getBody() {
return $this->responseBody;
}
protected function _getHeaders() {
return $this->responseHeaders;
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With