Abdulaziz
Abdulaziz

Reputation: 2211

Creating a class to store callback functions, is this method okay?

I have a function, which in basic terms, does the following:
initiates variables --> while loop -> store result in database.
but, since various parts of my project uses this function, I had to add callback functions for each step, to give myself some flexibility.

My current implementation looks like this:

function doStuff(arg1, arg2, $callbacks = array())
{
    //Init vars
    $var1 = ...
    $var2 = ...

    $callbacks['onStart']();//callback..

    //Loop:
    while(....)
    {

       $callbacks['afterCycle']; //callback after each loop.
    }

    //Database storage.
    $this->store($data);

    $callbacks['onEnd'](); //callback...

    }  

But my current implementation for this function isn't satisfying for me, I think it's not easy to maintain the code, and if I ever wanted to create another similar function(init->loop->storage), I'll be repeating myself, and my code wouldn't be consistent, for example, the current after-loop callback function is called "afterCycle", but for another function, it could be called "afterLoop", which will make my code inconsistent and harder to understand.

My current thoughts on this is to create a class that stores these callback function in pre-defined public fields, so the names are unchangeable, also, the function doStuff will enforce passing an object of that callback class. I'm not sure yet if this new implementation is any good, that's why I'm asking here.

The new implemenation I have in mind would look like this:

function doStuff(arg1, arg2, Callback $callbacks)
{
    //Init vars
    $var1 = ...
    $var2 = ...

    $callbacks->onStart();//callback..

    //Loop:
    while(....)
    {

       $callbacks->afterCycle(); //callback after each loop.
    }

    //Database storage.
    $this->store($data);

   $callbacks->onEnd(); //callback...

    }  

Upvotes: 0

Views: 275

Answers (1)

You could use an interface

interface ICallBack {
    public function onStart();
    public function afterCycle();
    public function onEnd();
}

//So all the methods in ICallBack must be implemented within CallBack
class CallBack implements ICallBack {
    public function onStart() {
        //blah
    }       

    ...
}


function doStuff(arg1, arg2, ICallback $callback){
   //Init vars
   $var1 = ...
   $var2 = ...

   $callback->onStart();//callback..

   ....
}

Upvotes: 1

Related Questions