如何在PHP(Laravel 5)中为我的站点的所有传入连接保留单个实例类?

I am working on a Laravel 5 based web application, I have a class "Connection" that is implemented as a Singleton

<?php

class Connection{

private static $instance = NULL;
private static $connection = NULL;

private function __construct(){
    self::connection=API::openConnection(); //just an example of connection (from other class) 
}

public function getInstance(){


    if(NULL==self::$instance)
    {
        self::$instance=new Connection;
    }  

    return self::$instance;

}

Now the problem I am facing is that, Whenever a connection fetches the instance and instantiates it for first time and opens the connection, but when other user visits the same page (earlier user visited), a connection is reopened(i.e. the class is instantiated again), The openConnection() can give only one connection at a time and the previous one closes when new user opens connection.

Is there any solution that I can use the single connection for multiple user requests?

Note:- Above code is just an abstraction of real problem, to get an idea.

Thanks for any help.

If I'm reading your question correctly, you're asking if it's possible to have a connection open on one request, and then have other users visiting the page use that connection without re-opening it.

The answer to your question, on a purely PHP level, is no. PHP was designed to be a stateless system. Each request that comes into the system forces the program to build up its state, and then that state is lost at the end of every connection. This was in alignment with system design styles at the time, which were all aping HTTP. The pattern you're describing is more common in a desktop or server computing programming environment, where an application stays resident in memory.

What you will find in PHP is third party libraries that enable the sort of persistent connections you're talking about. For example, the oracle driver (oci8) has a connect function , and a pconnect function. The later implements a persistent connection. These libraries can do this because they're implemented in C/C++ -- i.e., not pure PHP. Also, each library will have its own rules for what "persistent" means.

When you implement a singleton in PHP, what you're getting is an object that will always be that singleton object for that request only. It's a similar concept to a singleton in java, but because of PHP's vastly different run-time model, you end up using singletons very differently in PHP than you would in systems like java.

Hope that helps, and good luck!

You can’t share a connection between two different requests. A PHP script is interpreted and then when it reaches the end of the file, the response is returned and resources (including pointers to database connections) are freed.