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.
Best Answer
First off, "defining" and "declaring" are things you do in source code, rather than at runtime. Some variable declarations and definitions correspond to actual machine code that gets executed, and some do not. As far as I know, the definition of an additional function parameter or local variable will not generate any additional machine code, but will merely change how many bytes the CPU's frame/stack/etc pointers get moved as part of the function call.
What is true is that memory for a function parameter gets allocated on the stack every time you call that function (by the aforementioned pointers being moved), while memory for a global variable only gets allocated once. In that sense you're absolutely right. But the memory allocated by those function calls will also be immediately deallocated when the function exits, while the global variable's memory has to stick around for the entire length of the program. In that sense "more memory will be used" is not really correct.
Of course, this would be a very silly reason to use a global variable, because any change in memory usage or runtime performance is likely to be extremely tiny or totally nonexistent, while adding global variables you don't need usually makes programs far more brittle and untestable in the long run (see Why is Global State so Evil? for more on that). Definitely do not do it unless you have hard data from profiling tools that shows the global variable "optimization" is actually a big performance win over the local variable.