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

souvikbhattacharyas's avatar

Singletone not working in Laravel

Hi, I have a status List table and wants to load all the status on run time and kept it into the map for future use during the project lifetime. So, I have choose to use single tone structure (Don't wants to use cache for a very small record set). So, approach I have taken -

I have written a StatusDetailsUtiity class which will load the status list during the object creation.

public function __construct()
{
    // Load status during object creation.
    $this::loadStausDetails();
}

public static function getInstance()
{
    Log::debug("Single getInstance called");
    return app('T2R_Status');
}

Then load the single tone class I used AppServiceProvider - boot() method.

$this->app->singleton('T2R_Status', function ($app) { return new StatusDetailsUtiity(); });

Now the problem is on every request from browser it creates new object.

Can you tell me where is the problem.

0 likes
17 replies
jlrdw's avatar

Static don't need new keyword, static is like:

<?php

namespace App\Helpers;

class Clnsantize
{

    public static function fixValue($rvalue)
    {
        $rvalue = empty($rvalue) && !is_numeric($rvalue) ? NULL : trim(strip_tags($rvalue));
        return $rvalue;
    }

// more 

In controller a use statement like:

use App\Helpers\Clnsantize as Cln;

And usage:

$dogpic = Cln::fixValue($newname);

The new keyword is for non-static class methods, unless you use

public static function __callStatic($method, $params)
// more
souvikbhattacharyas's avatar

Hi, Didn't get what you are trying to mention. My problem is in every http request new singletone instance is getting created instead of a single object for project lifetime.

jlrdw's avatar

Then you probably need to study some topics in the php manual. Specifically static methods.

Snapey's avatar

Singleton only lasts for the request cycle. Only cache and session storage persist from one request to the next.

So, yes. I would expect the table to be loaded for every browser request

1 like
souvikbhattacharyas's avatar

Hi, Then can you suggest me to have a process to have a singletone for project life cycle. Because I will need to load the status table for nly once and every time it should be fetched from the loaded value.

jlrdw's avatar

It's not going to stay loaded, I gave you an example of static call usage. No different than Request, Session, or any class or facade, you have to call it when needed, and you have to have a use statement.

Now I am confused on you not understanding this.

souvikbhattacharyas's avatar

I understand the concept but with a background of Java I am looking for singletone. In java if you create a singletone class it should remain for project life cycle. So, is there anyway to do that.

jlrdw's avatar

I think you misunderstand Singleton. It means one instance, not an instance that stays loaded. It is there anytime to call a method. In fact it's the opposite of remaining loaded.

Take a look at this a singonton db class. It does not stay loaded. Rather singonton means one occurance only, it prevents several instances loading at once. In a instance method, you could have several new calls to a class, not a singleton.

Bottom line, it's used as needed, not loaded over and over again. In fact never loaded, static classes always available.

<?php

namespace Helpers;

use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Container\Container;
use Illuminate\Events\Dispatcher;
use PDO;

class DbPdo
{

    protected static $dbh = null;

    protected function __construct()
    {
        
    }

    protected function __clone()
    {
        
    }

    public static function dbh()
    {

        if (self::$dbh === null) {
            try {
                // I've run into problem where
                // SET NAMES "UTF8" not working on some hostings.
                // Specifiying charset in DSN fixes the charset problem perfectly!
                $opt = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
                $dsn = DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8';
                self::$dbh = new PDO($dsn, DB_USER, DB_PASS, $opt);
                return self::$dbh;
            } catch (PDOException $e) {
                //in the event of an error record the error to ErrorLog.html
                Logger::newMessage($e);
                Logger::customErrorMsg();
            }
        } else {
            return self::$dbh;
        }
    }

    /**
     * run raw sql queries
     * @param  string $sql sql command
     * @return return query
     */
    public static function raw($sql)
    {
        return self::dbh()->query($sql);
    }

    /**
     * method for selecting records from a database
     * @param  string $sql       sql query
     * @param  array  $array     named params
     * @param  object $fetchMode
     * @param  string $class     class name
     * @return array            returns an array of records
     */
    public static function select($sql, $array = array(), $fetchMode = PDO::FETCH_OBJ, $class = '')
    {
        $stmt = self::dbh()->prepare($sql);

        foreach ($array as $key => $value) {
            if (is_int($value)) {
                $stmt->bindValue("$key", $value, PDO::PARAM_INT);
            } else {
                $stmt->bindValue("$key", $value);
            }
        }

        $stmt->execute();

        if ($fetchMode === PDO::FETCH_CLASS) {
            return $stmt->fetchAll($fetchMode, $class);
        } else {
            return $stmt->fetchAll($fetchMode);
        }
    }

    public static function selectOne($sql, $array = array(), $fetchMode = PDO::FETCH_OBJ, $class = '')
    {
        $stmt = self::dbh()->prepare($sql);
        foreach ($array as $key => $value) {
            if (is_int($value)) {
                $stmt->bindValue("$key", $value, PDO::PARAM_INT);
            } else {
                $stmt->bindValue("$key", $value);
            }
        }

        $stmt->execute();

        if ($fetchMode === PDO::FETCH_CLASS) {
            return $stmt->fetch($fetchMode, $class);
        } else {
            return $stmt->fetch($fetchMode);
        }
    }

    /**
     * insert method
     * @param  string $table table name
     * @param  array $data  array of columns and values
     */
    ///   More methods
}

I wish I had the mental smarts to explain it better.

Please, please google singleton, and study this stuff.

Singleton, static calls, etc has nothing to do with a list of data staying loaded.

I have a status List table and wants to load all the status on run time

Put in a temp table, or hard code an array, or use csv file.

souvikbhattacharyas's avatar

I think u mis understand the concept or what I am trying to ask. Also it may differ technology or framework wise. But I am telling for Java.

Singletone is all about one instance of the object. This one instance does not depends on the request and response. So, in java if I load a class on start up and kept the object then whenever I will do getInstance() it will return the same object with same hascode. Now its my personal logic that I will keep data in that object or not.

But here in laravel for http request it creates a new object but within same request it keeps as a singletone.

So, my question was very simple that can I have anything like the same I used to do in java...

If this is not possible then I will go for some array or map to save my db calls.

Snapey's avatar

PHP is not Java. PHP is stateless and each request fires up the entire framework. This is not a Laravel thing.

If you don't want to load from the database each time, cache the results of the query.

reading: https://laravel.com/docs/5.7/cache

souvikbhattacharyas's avatar

@SNAPEY - Thats all I wanted to know. I will find an alternative solution to resolved my issue.

Thanks for you clarification.

jlrdw's avatar

A list does not stay loaded in Java neither Singleton is Singleton, and static is static no matter the language.

You are confusing a loaded list with a static call the two have nothing to do with one another.

And I done said you can use a temp table.

Meaning a table you hard-code your list in that's always there.

If the list data changes update the table.

You are trying to make this harder than it has to be.

souvikbhattacharyas's avatar

@JLRDW - In java we can keep the class loaded in server till the server restart. So, if you keep a list with value loaded in the the object then it can be used without loading.

Now in forum I dont want to go to argue between java and php but you guys solved my issue and many thanks for the same.

My intention is to reduce the db call so I will find an alternate may be an array.

Thanks for the help.

jlrdw's avatar

I agree no arguments. But static methods don't load they are always available.

If your list is really small it's going to do no harm to load it on demand as needed via static call.

But I also have programmed in Java Technologies and I have never heard of a list staying loaded. I have used hard-coded lookup tables before.

For example you are looking which truck driver is going to do a certain load that's where a driver table comes in.

I loaded in a pop-up lookup table.

souvikbhattacharyas's avatar

@JLRDW - My status table is very small but for each request there would be 4-5 call to get details of multiple status.

In case of java what I would prefer that I will write a singletone class where when it initialze(Constructor) I will fetch the records and will create a hashmap. Now I can fetch it without database call.

Now to make it single tone I will make the constructor private and from a getInstance method Inwill check if the object already initialized and if yes will return the same object which hold the hashmap with value.

Now this object will remain in java memory and will be available and I will also avoid the database calling more then once.

Please or to participate in this conversation.