1

I have a function that could be used in CLI or web application, that being said, there is a little difference in the process; for example: if I'm using this function for CLI it'll use a text progress bar, but that doesn't make sense if I'm using this function for a web application.

The function is basically a loop; so what i'm looking for is a way to make this function flexible by making it possible to pass code as an argument so that it'll be executed at the end of each loop cycle. So if I'm using this function in CLI; i'll pass a progress incremental function to advance the progress bar, and so on.

My current solution is to pass a progress bar object instance, which I think isn't a proper solution; because it doesn't seem flexible for the long run.

A demonstration example of what I'm already doing:

function myFunction($progressBar = null) { for($i = 0; $i......) { //Do stuff .... //finally... if(!empty($progressBar)) $progressBar->advance(); } } 

So, if I want to add another function at the end of the loop, I'll have to pass it as an argument and call it manually later; but as I said, it just doesn't seem right.

I'm thinking of using a callback function(an anonymous function being passed to myFunction) But what is a proper way of doing that; should I just make each callback function as an individual argument? or, to make it even more flexible, should I be grouping all callback functions in an array(if that's possible).

1 Answer 1

1

Yes, you can use callbacks for this.

function myFunction($progressBar = null, callable $callback = null) { for($i = 0; $i......) { //Do stuff .... //finally... if(!empty($progressBar)) $progressBar->advance(); } if ($callback){ //Execute the callback if it is passed as a parameter $callback(); } } 

Also, you can specify parameters for an anonymous function:

Example: you want to echo something at some point.

myFunction($progressBar) ; //No need yet myFunction($progressBar, function($result){ echo $result ; }) ; //Now you want to execute it 

So, handle it in an appropriate way:

if ($callback){ //Execute the callback if it is passed as a parameter $callback("All is fine"); //Execute the callback and pass a parameter } 

Array of callbacks also may be useful in this case like:

$callbacks = array( "onStart" => function(){ echo "started" ; }, "onEnd" => function(){ echo "ended" ; } ) ; function myFunc($progressBar = null, $callbacks){ if (isset($callbacks["onStart"]) && is_callable($callbacks["onStart"])){ $callbacks["onStart"]() ;//Execute on start. } //Execute your code if (isset($callbacks["onEnd"]) && is_callable($callbacks["onEnd"])){ $callbacks["onEnd"]() ;//Execute on end. } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.