Must Call This Function!

June 30th, 2009 | by Ozgur Cem Sen |

I was going through some code refactoring today, and needed a certain set of classes calling a particular function during their initialization.

I needed the function to be absolutely (i mean absolutely) implemented by any deriving classes of the base object.

I needed the function called automatically, so I won’t have to remember calling it anytime I derive something new out of the base class.

So, here is how I accomplished this lovely must-call-this-function pattern.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
interface ISample
{
    public function makeSureThatThisFunctionIsCalled();
}

abstract class ASample extends TheParentClass implements ISample
{
    public function __construct ($someParams)
    {
        parent::__construct($someParams);

        $this->makeSureThatThisFunctionIsCalled();
    }
}

class Sample extends ASample
{
    public function __construct($someParams)
    {
        parent::__construct($someParams);
    }

    public function makeSureThatThisFunctionIsCalled()
    {
        // do whatever you need to do here....
    }
}

class AnotherSample extends ASample
{
    public function __construct($someParams)
    {
        parent::__construct($someParams);
    }

    public function makeSureThatThisFunctionIsCalled()
    {
        // do whatever else you need to do here....
    }
}

The code should be self explanatory for the OOP savvy folks. Here is a very short description of what happens here.

Our actual class “Sample” extends the abstract class “ASample” which in turn implements the interface “ISample” (don’t worry about extending the TheParentClass). Implementing the “ISample” will require us to actually implement the makeSureThatThisFunctionIsCalled() function somewhere either in “ASample” or “Sample” class. We need class specific implementation of the function, so “Sample” and “AnotherSample” classes implement it.

Oh great, yay! We enforced our derived classes implement a function of the interface. Big deal!

How will we make sure that “makeSureThatThisFunctionIsCalled()” function will actually get called ?

In this sample, all the deriving class constructors call their parent::_construct which keeps bubbling up to TheParentClass so on and so forth…

So, we simply stick in “makeSureThatThisFunctionIsCalled()” in the immediate parent’s constructor and tada !!!

Our must-be-called function is surely getting called during the object’s initialization.

This may sound like a glorified initializer, but you never know. You may just need something like this.

Sorry, comments for this entry are closed at this time.