1. Home
  2. Docs
  3. Application Framework
  4. Classes & Patterns
  5. Singletons

Singletons

MWP\Framework\Pattern\Singleton

The singleton is an important and frequently used design pattern. It ensures that only one instance of a given class can exist, and it provides an easy way to access that instance from anywhere. A singleton protects against multiple copies of a class being created, either purposely or inadvertently. It should be used any time that it makes sense for a given class to only ever have one instance of itself in circulation.

To implement the singleton design pattern:

  • Extend the MWP\Framework\Pattern\Singleton base class
  • Make sure to define the protected static $_instance property inside your class.

@Example Code

namespace VendorName\PackageName;
use MWP\Framework\Pattern\Singleton;

class MyClass extends Singleton
{
    /**
     * @var object    All singletons must define this property
     */
    protected static $_instance;

    /**
     * Initialize
     *
     * @return    void
     */
    protected function constructed()
    {
        // optional initialization routine when the instance is first constructed
    }
}

@Static Method Reference

Singleton::instance()

To access your singleton instance from anywhere, use:

use VendorName\PackageName\SingletonClass;
$instance = SingletonClass::instance();
Was this article helpful to you? Yes No

How can we help?