Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Preface: I am working in PHP (Abandon hope all ye who enter here).

Background: There exists a large set of global functions in PHP, a number of which are miscellaneous system calls, like sleep (and others). Now, I use sleep (and others) in a bunch of different scripts I run in a bunch of different places, and I have found I need sleep to call pcntl_signal_dispatch as soon as the sleep finishes- but possibly not in all my scripts.

A Generalization: I need to make global function do more than it currently does, hopefully without disrupting my current ecosystem too much.

My Solution: I figure I could create a wrapper class that executes the correct "sleep".

Singleton: I could make a singleton "System" class that wraps the global functions. Hell, I could even make the wrappers static methods. The downside is that there would be a lot of boilerplate checking to see which version I would need to execute, either a vanilla function call or one with extra stuff.

Global variable: I could make a generic "System" class that wraps the global functions. I could then extend the System class with different classes that override the wrapper functions. I create a global System variable within each script, dependent upon how I need the functions to behave. All my scripts have access to that global variable. The downside is I would have to make sure the global variable is declared, is never overwritten, and uses the proper System.

Something else: I could create a SysControl class with a static System variable and static wrappers of the System's wrappers of the functions, and then swap out which System my SysControl class references. The downside is that I feel I am going overboard.

Are there any more options I should consider? Which of these methods is the best, and why? What pitfalls should I look for going forward?

EDIT: I ended up using the Something else solution.

share|improve this question
    
Does PHP not have first-class functions? I'm not versed enough in PHP to actually answer, but stay away from singletons, globals, or static variables. Invisible dependencies are not good. Find a way to pass in the right function to your scripts without requiring someone to mutate some global state before calling it. – Doval Apr 15 '14 at 0:48
    
@Doval The problem is, if I pass in functions as arguments, that will get very out of hand very quickly. – MirroredFate Apr 15 '14 at 0:54
1  
More quickly than using a Singleton as a switch yard? – Robert Harvey Apr 15 '14 at 3:49
    
@RobertHarvey Quite possibly, yes. If I have functions A, B, C, and D, and A calls B which calls C which calls D, and I have to pass through four functions in addition to their normal arguments, and I have this situation everywhere, that does not seem maintainable at all. Far less maintainable, in fact, than using a Singleton or global... I total agree with Doval about invisible dependencies- they have the tendency to cause headaches- but other solutions seem worse (hence the question). – MirroredFate Apr 15 '14 at 17:24
    
Would the use of namespaces actually increase the mess, or provide another alternative ? – mika Apr 16 '14 at 8:58
up vote 2 down vote accepted

Preface

For any given project, the answer to this question will likely differ. This is simply a result of structure and overall philosophy. It may be easy and straightforward in some instances, but extremely difficult and complicated in others.

However, if this is a difficult problem, that is a very strong code smell: something is likely quite wrong with your project. That being said, we've all been there, and we often don't have time to rewrite the entire codebase. Still, to start: what's the right way to solve this?

The Right Way

IoC (Inversion of Control) is a design pattern and principle that has steadily gained traction. It basically states that instead of objects building what they need, they request an instance of what they need from some IoC container, which can give them the appropriate "thing".

In this case, we could do something like the following:

interface SystemAdapterInterface
{
    public function sleep($duration);
}

class WakefulSystemAdapter implements SystemAdapterInterface
{
    public function sleep($duration)
    {
        sleep($duration);
        pcntl_signal_dispatch();
    }
}

class SleepySystemAdapter implements SystemAdapterInterface
{
    public function sleep($duration)
    {
        sleep($duration)
    }
}

class SleepingEntity
{
    public function __construct(SystemAdapterInterface $system)
    {
        $this->system = $system
    }

    public function mayReceiveSignal()
    {
        $this->system->sleep(100000);
    }
}

// Register the system and sleeping entity with the IoC Container
// Using the LoEP Container for IoC
$container = new League\Container\Container;

$container->add('SystemAdapterInterface', 'WakefulSystemAdapter ');

$container
    ->add('SleepingEntity')
    ->withArgument('SystemAdapterInterface');

//Now we can easily get an instance of sleeping entity.
$container->get('SleepingEntity');

In this example, we use an IoC container to manage what System SleepingEntity uses. My recommendation for an IoC is Container, from the League of Extraordinary Packages.

This solution keeps our SleepingEntity decoupled from our System. Depending on where we use SleepingEntity, we can simply configure our IoC Container differently. It's nice because it's relatively simple, easy to test, and allows for expansion in the future.

Unfortunately, this doesn't work particularly well if you already have a whole lot of code with sleeps (or similar global function calls), and you need to modify their behavior. So what can we do about that?

The Not Quite as Right Way

Ok, so you want to do The Right Thing, but the code is poorly documented, has dependencies intertwined every which-way, and it is an incredibly heavy lift to go through and make sure you've passed your IoC every which way down the tree until it is used to instantiate the right object, every time.

The best thing to do is to be forward-looking. If you want to make the codebase better, more decoupled, take the first step with this addition.

Let's say you have the following:

class DoSomethingAndSleep
{
    public function foo($a, $b, $c)
    {
        $a->thing();
        $b->thing();
        sleep(5);
        $c->thing();
    }
}

Now let's pretend that DoSomethingAndSleep is used 1,000 different places by all kinds of different code. In fact, it is sometimes instantiated anonymously through an class variable, so finding those 1,000 places is hard. Really, really hard.

Fine. Let's just move the decoupling goodness into DoSomethingAndSleep. Hopefully you'll have time to refactor things one by one in the future.

class DoSomethingAndSleep
{
    public function __construct(SystemAdapterInterface $system=null)
    {
        if ($system=== null)
        {
            $system = App::getIoC()->get('SystemAdapterInterface');
        }
        $this->system = $system;
    }

    public function foo($a, $b, $c)
    {
        $a->thing();
        $b->thing();
        $this->system->sleep(5);
        $c->thing();
    }
}

Ok, so what's going on here? Well, there is firstly a recognition that we don't have the right infrastructure to pass the the IoC into DoSomethingAndSleep, or to use it to construct the DoSomethingAndSleep, so instead we're going to bypass all of that and get the "standard" IoC from our App. This means that upon application startup, we have to:

  • instantiate the IoC Container
  • register the SystemAdapterInterface with the IoC Container
  • register the IoC Container with the App

This is acceptable. As we have a default argument in our DoSomethingAndSleep constructor, we can spend time moving forward refactoring things to use the IoC Container without breaking backwards compatibility.

We still will need to move to (hopefully) using the Container to manage objects and instances, but at least we're at a point where we are registering the SystemAdapterInterface and using the registered one instead of directly instantiating it.

If you are using the League Container, we can even register DoSomethingAndSleep with our IoC Container using this method, and leverage the Auto Wiring and the Reflection Delegate to take care of this new dependency for DoSomethingAndSleep.

$container = new League\Container\Container;

// register the reflection container as a delegate to enable auto wiring
$container->delegate(
    new League\Container\ReflectionContainer
);

$doSomethingAndSleep = $container->get('DoSomethingAndSleep');

This should make our future refactoring go even more smoothly.

Conclusion

It is always difficult to figure out how to take an old, monolithic codebase and slowly make it better, more maintainable. You can't break backwards compatibility, you need to move forward with new features, and you want to make sure the additions improve things. That's tough. I think the best suggestion is this: if you can't write tests for it, you will have a terrible time maintaining it. So every time you make a change, make sure you can write a unit test against that change.

In this case, using IoC accomplishes this with very little effort. Even if your project isn't structured to use it, you can introduce it initially and only use it in one place, and then over time you can refactor your code until eventually everything is using DI and is pleasantly decoupled.

share|improve this answer
    
To do it really "the right way", shouldn't SleepingEntity receive all parameters in the constructor instead of the whole IoC container? – Matteo Tassinari Jun 22 at 8:57
    
Good point. I'll revise a bit. – MirroredFate 2 days ago
    
When I initially wrote it I was trying to keep it "container agnostic", but that's not particularly realistic. I'll just use the League Container. – MirroredFate 2 days ago

Are there any more options I should consider?

  • have a look at php constants instead of global variables
  • consider using bit fields instead of a SYSTEM variable or constant
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.