Use a global variable, a singleton, or something else

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.

10

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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 LeagueContainerContainer;
$container->add('SystemAdapterInterface', 'WakefulSystemAdapter ');
$container
->add('SleepingEntity')
->withArgument('SystemAdapterInterface');
//Now we can easily get an instance of sleeping entity.
$container->get('SleepingEntity');
</code>
<code>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 LeagueContainerContainer; $container->add('SystemAdapterInterface', 'WakefulSystemAdapter '); $container ->add('SleepingEntity') ->withArgument('SystemAdapterInterface'); //Now we can easily get an instance of sleeping entity. $container->get('SleepingEntity'); </code>
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 LeagueContainerContainer;

$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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class DoSomethingAndSleep
{
public function foo($a, $b, $c)
{
$a->thing();
$b->thing();
sleep(5);
$c->thing();
}
}
</code>
<code>class DoSomethingAndSleep { public function foo($a, $b, $c) { $a->thing(); $b->thing(); sleep(5); $c->thing(); } } </code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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();
}
}
</code>
<code>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(); } } </code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>$container = new LeagueContainerContainer;
// register the reflection container as a delegate to enable auto wiring
$container->delegate(
new LeagueContainerReflectionContainer
);
$doSomethingAndSleep = $container->get('DoSomethingAndSleep');
</code>
<code>$container = new LeagueContainerContainer; // register the reflection container as a delegate to enable auto wiring $container->delegate( new LeagueContainerReflectionContainer ); $doSomethingAndSleep = $container->get('DoSomethingAndSleep'); </code>
$container = new LeagueContainerContainer;

// register the reflection container as a delegate to enable auto wiring
$container->delegate(
    new LeagueContainerReflectionContainer
);

$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.

3

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Use a global variable, a singleton, or something else

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.

10

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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 LeagueContainerContainer;
$container->add('SystemAdapterInterface', 'WakefulSystemAdapter ');
$container
->add('SleepingEntity')
->withArgument('SystemAdapterInterface');
//Now we can easily get an instance of sleeping entity.
$container->get('SleepingEntity');
</code>
<code>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 LeagueContainerContainer; $container->add('SystemAdapterInterface', 'WakefulSystemAdapter '); $container ->add('SleepingEntity') ->withArgument('SystemAdapterInterface'); //Now we can easily get an instance of sleeping entity. $container->get('SleepingEntity'); </code>
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 LeagueContainerContainer;

$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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class DoSomethingAndSleep
{
public function foo($a, $b, $c)
{
$a->thing();
$b->thing();
sleep(5);
$c->thing();
}
}
</code>
<code>class DoSomethingAndSleep { public function foo($a, $b, $c) { $a->thing(); $b->thing(); sleep(5); $c->thing(); } } </code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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();
}
}
</code>
<code>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(); } } </code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>$container = new LeagueContainerContainer;
// register the reflection container as a delegate to enable auto wiring
$container->delegate(
new LeagueContainerReflectionContainer
);
$doSomethingAndSleep = $container->get('DoSomethingAndSleep');
</code>
<code>$container = new LeagueContainerContainer; // register the reflection container as a delegate to enable auto wiring $container->delegate( new LeagueContainerReflectionContainer ); $doSomethingAndSleep = $container->get('DoSomethingAndSleep'); </code>
$container = new LeagueContainerContainer;

// register the reflection container as a delegate to enable auto wiring
$container->delegate(
    new LeagueContainerReflectionContainer
);

$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.

3

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Use a global variable, a singleton, or something else

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.

10

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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 LeagueContainerContainer;
$container->add('SystemAdapterInterface', 'WakefulSystemAdapter ');
$container
->add('SleepingEntity')
->withArgument('SystemAdapterInterface');
//Now we can easily get an instance of sleeping entity.
$container->get('SleepingEntity');
</code>
<code>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 LeagueContainerContainer; $container->add('SystemAdapterInterface', 'WakefulSystemAdapter '); $container ->add('SleepingEntity') ->withArgument('SystemAdapterInterface'); //Now we can easily get an instance of sleeping entity. $container->get('SleepingEntity'); </code>
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 LeagueContainerContainer;

$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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class DoSomethingAndSleep
{
public function foo($a, $b, $c)
{
$a->thing();
$b->thing();
sleep(5);
$c->thing();
}
}
</code>
<code>class DoSomethingAndSleep { public function foo($a, $b, $c) { $a->thing(); $b->thing(); sleep(5); $c->thing(); } } </code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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();
}
}
</code>
<code>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(); } } </code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>$container = new LeagueContainerContainer;
// register the reflection container as a delegate to enable auto wiring
$container->delegate(
new LeagueContainerReflectionContainer
);
$doSomethingAndSleep = $container->get('DoSomethingAndSleep');
</code>
<code>$container = new LeagueContainerContainer; // register the reflection container as a delegate to enable auto wiring $container->delegate( new LeagueContainerReflectionContainer ); $doSomethingAndSleep = $container->get('DoSomethingAndSleep'); </code>
$container = new LeagueContainerContainer;

// register the reflection container as a delegate to enable auto wiring
$container->delegate(
    new LeagueContainerReflectionContainer
);

$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.

3

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật