Singleton standard for database communication

Asked

Viewed 411 times

2

In PHP when I do a Singleton is created an instance for each request that tries to open a connection to the database or instantiating a single time she "always" will stay in memory for all requests?

example:

class Connect{

    private static $conn;//qual o escopo dessa variavel?

    /**
    *   Padrão singleton
    */
    public static function getConnection(){
        if(self::$conn==NULL){
            //vai entrar aqui toda vez que uma requisição do usuario tenta uma comunicação com o bd?
            self::$conn= new PDO(...);
        }       
        return self::$conn;
    }
  • I don’t know much about php, but something tells me that the code is wrong, like the private variable and static. I think the variable should be private only and the yes method should be static. Please correct me if I’m wrong.

  • It’s not wrong. Singleton is just like that in PHP. You need a static variable (because it is static, rsrs), and so the instance will remain active inside. Then, if it is null (which will only happen once), it instantiates PDO. If not, it returns the connection already instantiated. There is nothing wrong (with the code, I don’t mean the use of Pattern)

  • @Rubico There is no way to access an instance member using the static method. Which instance would you be talking about? Actually there are cases in the pattern that do the opposite and there are instance methods (not all) that access static members (normal since there is only one).

  • Forget it, guys, I was full of shit. Just as @Wallacemaxters said, it should be static, otherwise its state would be preserved by the instance and not by the class.

1 answer

4


The Singleton pattern is just that (it can eventually be a little more sophisticated). Because it is static there is no actual instantiation, and the logic of the method ensures that the connection is opened only once, after all, the first time the private variable $conn, which has a private scope (only the class sees it), is null then a connection is established, after which it no longer enters the if and only returns the connection object. Then it will remain in memory while the script is spinning.

I often say that this sort of thing is too complicated for something that will be very ephemeral, but it’s fashionable to do so. Design Patterns are usually abused, Singleton is the champion of this, in PHP then...

  • I don’t understand the negative. Singleton is well explained. And I agree, really the abuse that occurs in this, it sometimes seems to leave the application in a cast.

  • What do you mean by abused? I’m sorry but I couldn’t understand.

  • @Rubico uses when you don’t need it. You can do something simple, you choose the complicated.

  • If you need it once, why not just instantiate it once? Is it so hard? Sometimes Singleton is just an unnecessary complication

  • @Wallacemaxters understand your point of view, but if it is something that must be instantiated only once, why not avoid human failure? Maybe a new and unsuspecting developer can start creating several instances and this will be detrimental to your project. Singleton is a valid thing in this case, no?

  • 1
  • Trying to correct the lack of information of a programmer with code does not find a very pleasant solution. Singleton is not at all useless, but sometimes unnecessary. That’s what I mean.

  • 3

    I have nothing against Singleton. I find him useful. I just think he’s abused. Of course, sometimes other patterns are even more abused to avoid Singleton :) In PHP, a lot of things are abused because it’s fashionable to do complex things where you don’t need them. Then the guy who thinks the complex is good negative answers that tell him what he doesn’t like. Precisely why the person does not comment saying where is the error of the answer.

  • Guys didn’t want to argue about Singleton, there will never be an end, I’ve read several subjects about it, the main question is, each user makes a request to my server. each request accesses n times the bank, my question is, the statical variable will be one for each request or one for all requests?

  • I believe that answer is wrong. Since php opens a process and kills it at the end of the request Singleton will not be the same between two requests. Within a request Singleton works as expected, but between requests it does not.

  • More specifically who kills the php process is the web server. In the case of being Apache it will be a process by request in the case of using php-fpm it manages the processes not to be using one per connection, but in the same way it kills the process frequently.

  • 2

    @Viniciuszaramella I did not say this, on the contrary, I spoke the opposite of what you are quoting. It will keep the connection open while the script running. That’s why using these things in PHP makes so little sense.

  • Yes, but in a request in my case can be opened several communications with BD, so I found it interesting to keep an open connection by request not to keep creating for example 5 connection in a single request. Imagine 100 requests open 500 connections to the comic. So I thought I’d do Singleton. Thanks for the answer, what I wanted to know was exactly that "while the script is running." , I was a little confused as to the scope of a class statistical variable, whether its value was seen for any request.

  • What can happen too, I’m using PDO, but it could be another class of communication, I haven’t gone into how it works, sometimes it can even create a pool of connections. That would be another story, so it wouldn’t even make sense to do English. But I am not saying anything, only that I do not know how it works, and to discuss it would already fit in another question or a read in the documentation would already answer.

  • regarding the pool this there, very interesting http://answall.com/questions/26873/management-de-connection-pooling-pelo-pdo

  • But why would you open multiple connections in a request? For years I worked in one of the most crude languages to manage connections with database and other code organizations, I did not know Singleton or similar solution, the codes were absurdly larger and more complex than any script PHP, and I’ve never had trouble opening the same connection twice. Scope is one thing, visibility and lifetime are different things. Singleton, Pool, all this can be useful but not at 99% (or more) of scripts PHP. PHP is not Java.

  • For example a request needs to make a 5 selects or more, to recover data from an object, it would be interesting to keep the connection open, I see from that point of view.

  • 1

    Yes, but it stays open until it is closed. Open, make 5 and close at the end of script (or let it close by itself, even if I don’t like it). There’s no reason to keep opening and closing. I understand that a lot of people are doing this, but I don’t know why. There’s no reason to do it, it’s just something wrong that people keep copying. That is why I say that people need to learn to program and not follow "good practices". You need to understand what’s going on with the code and make the best decision. Programming is looking for the best solution and not copying others' errors.

Show 13 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.