Reputation: 1857
I have the following pattern of code in a lot of methods:
$attempts = 0;
do {
$response = $this->DOSOMETHIING($data, $info);
sleep(1);
$attempts++;
} while ($attempts < 5);
What I would like to do is have a helper method for this while loop that can somehow be sent a specific method call. So something like this:
$response = $this->execute($this->DOSOMETHIING($data, $info));
The helper method:
function execute($method){
$attempts = 0;
do {
$response = $method(); <<< I know!
sleep(1);
$attempts++;
} while ($attempts < 5);
return $response;
}
The trouble is that the method call being sent to the helper method will be one of 3 different method calls and they all have a different number of parameters, so it's not like I can send the method and the parameters separately.
Upvotes: 1
Views: 46
Reputation: 7875
Looks like you need closure pattern : http://php.net/manual/en/class.closure.php
bellow code use same "execute" function for two kind of traitment :
public function __construct() {
}
public function execute($method) {
$attempts = 0;
do {
$response = $method();
sleep(1);
$attempts++;
} while ($attempts < 5);
return $response;
}
public function foo($data, $info) {
//Do something
return array_merge($data,$info);
}
public function bar($other) {
echo 'Hello '.$other;
}
public function main() {
$data = ['foo' => 'bar'];
$info = ['some' => 'info'];
$other = 'world';
$return = $this->execute(function() use ($data, $info) {
return $this->foo($data,$info);
});
var_dump($return);
$this->execute(function() use ($other) {
$this->bar($other);
});
}
}
$tester = new Foo();
$tester->main();
Upvotes: 3
Reputation: 163
You could make use of call_user_func_array which will return the value of your callback.
Upvotes: 1