Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kinshara's avatar

singleton

I made widgets module, and Page class

when i load homepage, it will call several widgets to put in.. but the problem is the 2 widgets fetch the data from Page class.. and each widgets will create

$about = new Pages();
return $about->get('pages');
//first
$rules = new Pages();
return $rules->get('rules');

I wondered what if there is 3-4, it must create new Pages() 4 times,, is there any method for singleton?

0 likes
6 replies
kfirba's avatar
kfirba
Best Answer
Level 50

@kinshara Yes there is. If you want to use Laravel you can use its singleton method:

app()->singleton('Pages'); // include the namespace

Now whenever you need an instance of Pages simply do:

$var = app('Pages');

Done!

Also, you can make Pages a singleton class on your own which should not be difficult:

class Pages {

    protected static $instance;

    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    /**
     * Protected constructor to prevent creating a new instance of the
     * singleton via the `new` operator.
     */
    protected __construct()
    {
        // your constructor logic here.
    }

    /**
     * Private clone method to prevent cloning of the instance of the singleton instance.
     */
    private function __clone()
    {
    }

    /**
     * Private unserialize method to prevent unserializing of the singleton instance.
     */
    private function __wakeup()
    {
    }

}

Now simply whenever you need a Pages object:

$var = Pages::getInstance();

Good luck!

2 likes
kinshara's avatar
use gsjathi\Systems\Controllers\Systems;

abstract class Controller extends BaseController {

    use DispatchesCommands, ValidatesRequests;

    public function __construct() {
        $config = Systems::getInstance();
    }
}

@kfirba I got error.. Non-static method.. did i miss something?

pmall's avatar
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static();
        }

        return static::$instance;
    }

Note the static

thepsion5's avatar

Singletons are generally considered an anti-pattern, since any code using the singleton can have its instance altered at any time by code anywhere else. Do you have any specific reason for using one?

1 like

Please or to participate in this conversation.