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;
}
?>
Looks to me like you are overcomplicating this. (Assuming I understood your question.)
Why not just have the function that talks to the remote server set a flag when it is done?
Why do you need to check each stage of the connection? And why are they separate stages anyway? Don't they all work together in a specific order, and never from any other code? There isn't any reason to make them individual functions. (Unless there is more to your code that I don't know about.)
I'm not sure what you're doing...but if you want to intercept every method call.
class ObjectProxy {
protected $obj;
function __construct($obj) {
$this->obj = $obj;
}
function __call($methodName, $arguments) {
//do stuff
return call_user_func_array($methodName, $this->obj, $arguments);
}
}
$proxied = new ObjectProxy(new OrigionalType());
$proxied->getBody();
You probably want to implement more of the magic methods to make it work for more than instance method calls, but you get the point. It's not a solution for all situations, but can be handy at times.