1

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.

2
  • 1
    Something like a Callback / Callable? Commented Mar 14, 2018 at 10:14
  • It doesn't look like parameters are included in that. Commented Mar 14, 2018 at 10:16

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

Comments

1

You could make use of call_user_func_array which will return the value of your callback.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.