0

I read on the web that many developers are using singleton pattern for their PDO connections. [where?]

I've been using singleton patterns before (in VB.Net), and I'm quite sure that it's only useful when you have to call an instance twice or more [code example of .NET code missing].

I'm currently working on an e-commerce website, I'd like to know if it's really useful to use a singleton pattern on my PDO connections since my architecture is made in a way that each script only needs one connection [code example where you would use such a singleton missing].

hakre
  • 193,403
  • 52
  • 435
  • 836
Yonn Trimoreau
  • 539
  • 7
  • 23
  • In case the existing answers do not fully address your question, please provide the information I placed marker for in your current question with your new question. – hakre Sep 25 '13 at 15:52

1 Answers1

4

In response to the "comment-discussion" that this question (and perhaps answer) has ignited, a recap of my opinion, and the general consensus (don't skimp on equipment/server load, when that means doubling the man-hours and maintainability is more important than speed, save for a few specific cases).

You say you hate frameworks and that devs who use frameworks they didn't develop themselves sell maintainance contracts. How exactly does that work? Code using an open source, documented FW can be maintained by anyone who knows the FW. Your code can be maintained by you.
Besides, PHP frameworks are (well, the main ones at least) OPEN SOURCE. I know that, coming from a VB.NET background, you might suspect there is a catch to this, but there really isn't. They all have github repo's, the source is freely available to copy, and edit (in accordance to the license, which, on the whole is quite liberal anyway). Basically, you have full control.
And don't go thinking it's all second-grade code: Apple (including major parts of their OSX kernel), Microsoft, Google... they are all using open-source software and frameworks. Not only because it's easy, and faster to develop, but also because of the notion of proven technology.

Besides: performance is your goal, and -given that you loathe frameworks-, why not consider learning assembly? That way, you can avoid having an idiotic compiler compile your code to something that isn't as efficient as, perhaps, it could have been.
And of course, you don't use an IDE for this, you'd either go for Emacs or butterflies, right?

Emacs butterfly
(source: andreas-wilm.com)

An alternative approach would be to use a framework that offers advanced caching featrures...

Maintainability should be at the most important thing to you, while writing code:

'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.' — Brian Kernighan

Servers are zombie-slaves: they don't complain, and it's not illegal to whip them. Developers, though some project-managers seem to forget this, are neither zombies or slaves: they can't work 2 weeks on end, and whipping devs is illegal, still. Even Steve Ballmer knows that... Developers, Developers, Developers. Microsoft's Server OS's are resource intensive, as is MSSQL, and pretty much all their software, but look into their server OS. There are many features that only serve to reduce the maintainance hours your system requires. I'm no MS fan-boy, but I fully understand that descision. They can't beat Linux on price ('cause it's free), but they can lure in companies by selling a system, that will cut their sys-admin costs in half. (though, ATM, they haven't acchieved this, and IMO, they never will)


This question is one of many dupes, a bad fit for SO, and will be closed. However, before it gets closed/deleted, I'd like to point a couple of things out to you:

First things first:

As I'm currently working on an e-commerce website, I'd like to know if it's really useful to use a singleton pattern on my PDO connections

No, it never is.

injection PHP is not capable of persisting an objects' state in between requests. The server receives a request. The script is parsed, the DB connection is established, queries are performed, the response is sent back and the connection is closed. Over and over again.
Connections can't be serialized, they can't be stored in any way, shape or form, so:
By coding well, you can use injection and at the same time ensure that you only connect to the DB once per request.
Statics are globals in drag, now: would you use globals if you might as well pass an argument? Giving you the benefit of the doubt, I assume your answer is no.
The few remaining benefits of singletons that remain, then, are not worth the effort it takes to write decent, working, unit-tests for your singleton-using code.

Why:

my architecture is made in a way that each script only needs one connection.

Then your code isn't very scalable. I know this is a blanket statement, and a terrible cliché, but it just is the case here. Just like your presumtion that each script only needs one connection might be true right now, but who's to say that will always be the case?
Refactoring the DB, adding support for another adapter, testing (as mentioned before) become increasingly difficult, as you'll write code and, without noticing it, that new code will be adapted to maintain the singleton.
This means that you'll write code to preserve what was, because you're working around its problems, a bad design decision.

Think of it like this:
You build a house, and decide to build a concrete pilar into the corridor, because that's where you'll hang your coat-hangers anyway, and you'll never change that. But Singleton implies that you're writing OO code. The whole point is that you can re-use code. Now: do you honestly think that you'll be able to sell your house just as easily if it had an immovable coat-hanger, as it would be if that thing wouldn't be there? of course not!

And I'm quite sure that it's only useful when you have to call an instance twice or more.

If that's so: use another pattern, or take a leaf out of the Symfony book, and make the connection available to whatever object needs it using a container (dependency injection component is worth a google search).

Testing:

It's all been explained before, but testing singleton code is a nightmare. Learn to use injection.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • If you're talking about best practices, I **would not** recommend the Symfony2 DiC. It utilises the service locator anti-pattern. – Jimbo Sep 25 '13 at 14:16
  • @Jimbo: That's a different discussion, but note that one of the most avid advocates _against_ the service locator pattern also acknowledges [that it has its use cases](http://blog.ploeh.dk/2012/11/06/WhentouseaDIContainer/) – Elias Van Ootegem Sep 25 '13 at 14:22
  • Some argue that the Singleton has it's use cases as well. You should check out [Auryn](https://github.com/rdlowrey/Auryn), it's a brilliant DiC that recursively instantiates dependencies based on class signatures, and allows true SOLID code. – Jimbo Sep 25 '13 at 14:26
  • @Jimbo: I'm not saying Symfony's DiC is the best one out there, in fact Auryn works kind-of like how I tend to [lazy-load](http://codereview.stackexchange.com/questions/29649/db-query-within-foreach-non-elegant-code-in-general/29677#29677) dependencies... I only pass the config required to most of my objects, and use `getters`, that create the dependencies if they are required – Elias Van Ootegem Sep 25 '13 at 14:36
  • 1
    It seems we don't use the same language. I don't use OO code, I don't use any framework, my code is pure and optimized. And after all, it's an e-commerce website, it has to be simple and very responsive. Anybody using a framework is an idler who doesn't want his website to be fast and scalable. And I'm using multiple requests with a unique connection. – Yonn Trimoreau Sep 25 '13 at 15:07
  • @YonnTrimoreau: How do you implement the singleton pattern in procedural code? and how is PDO's API _not_ OO? BTW: using a framework is [being _cleverly lazy_, IMHO](http://blogoscoped.com/archive/2005-08-24-n14.html), and that's part of being a good programmer. I've written my own framework, but most of the time, I cherry pick from those that _already exist_ I don't reinvent the wheel. Saying multiple requests are using the same connection is worrying: you mean you're using _a persistent connection?_ How would _that_ scale (think about replecation, locks, clusters...) – Elias Van Ootegem Sep 25 '13 at 15:18
  • [Check this answer](http://stackoverflow.com/questions/3332074/what-are-the-disadvantages-of-using-persistent-connection-in-pdo): it only takes a single bug to cause your e-commerce site to be _down_. The larger the site gets, the more plausible the deadlock-timer scenario becomes – Elias Van Ootegem Sep 25 '13 at 15:22
  • @YonnTrimoreau Are you actually serious? Quote of the week!! "Anybody using a framework is an idler who doesn't want his website to be fast and scalable". LMAO. – Jimbo Sep 25 '13 at 15:38
  • 5
    @YonnTrimoreau You talk about avoiding OOP and frameworks because you want speed, yet you're using PHP and PDO, neither of which are high performance options. What you're doing is akin to refusing to open the windows in your car because the wind drag may impede top speed, meanwhile you refuse to stop driving your [Lada](https://en.wikipedia.org/wiki/File:Lada_2107_in_France.jpg). – Glitch Desire Sep 25 '13 at 15:49
  • 3
    @YonnTrimoreau *"Anybody using a framework is an idler who doesn't want his website to be fast and scalable."* - Also, this comment is in a whole new league of stupid. Servers are cheap, programmer hours are not. The fact that you'd sacrifice long term code maintainability for the ability to spend a little less on servers is poor business. Frameworks increase coder efficiency and maintainability in exchange for a little performance. Programmers make this exchange all the time, by choosing HLLs, to improve UX, to improve maintainability. That's not laziness, it's economic efficiency. – Glitch Desire Sep 25 '13 at 15:58
  • Elias : The only OO I use is PDO, and I'm not using persistent connection. I just meant that I use one connection for all my requests (which are all in the same script), and I think it's the right way, correct me if I'm wrong. And... deadlock-timer ?! Google doesn't seem to understand what you're talking about. @Jimbo I really hate frameworks because you don't have any control on your source code. And why making a framework Elias ? Your code will get longer and longer.. Maybe scalable, but slow.. Because it's not fitting what you need but more. – Yonn Trimoreau Sep 25 '13 at 16:09
  • @Starsong I'm actually learning other languages, I know PHP is not a good choice for speed. But PDO ? Explain please :) And I'm working for somebody who knows that a long, good and expensive work will operate better. – Yonn Trimoreau Sep 25 '13 at 16:12
  • 2
    @YonnTrimoreau You "hate frameworks" because of a lack of control? They're all on bloody github and you can contribute to source! Adding a new page and route using the templating system takes less than a minute. OOP interfaces allow you to shift out any connection from, say, MySQL to MongoDB in an instant. [Silex](http://silex.sensiolabs.org/) is a micro-framework that only gives you routing and a few other basics, and you can build it up modularly if (like me) you prefer your own architecture. Don't chalk devs who develop faster using frameworks as idiots, you're in the minority here. – Jimbo Sep 25 '13 at 16:14
  • @Jimbo Devs who develop faster using framework they have not developed themselves are one of them who sell maintenance contracts because they only think about money and cannot make it by themselves. I'm making great, optimized websites in less than a month without using OOP and frameworks. I sell it around 6k€, where can I complain ? – Yonn Trimoreau Sep 25 '13 at 16:19
  • @YonnTrimoreau No no, you *start out* with procedural code. **Then**, after years of experience, you pick up a framework and it handles all the repetitive tasks for you and makes your life easier. That's how it works, you don't just jump in. Put some effort in, learn an actual framework fully, then come back and tell us how it hasn't improved your workflow and ability to maintain with little effort. If you enjoy programming, you should at least be checking these things out anyway in your spare time. – Jimbo Sep 25 '13 at 16:24
  • @YonnTrimoreau: If you're not using any OO code, how are you using the singleton pattern? You _say_ you hate frameworks, but you have experience with VB.NET, which is, AFAIK, [_"implemented on the .NET Framework."_](http://en.wikipedia.org/wiki/Visual_Basic_.NET). Developing in a framework _is_ developing yourself: OOP is wide-spread, if you don't do OOP, you're not developing yourself. If you don't even _look_ into frameworks, you're not developing yourself. BTW: You're selling your site for 6k€? Where did you find the nutcases that are willing to pay _that_ much? – Elias Van Ootegem Sep 26 '13 at 06:15
  • @YonnTrimoreau One of the reasons we use higher level languages is to abstract away repetitive and tedious tasks (memory management, register allocation, stack handling). This is the exact same reason we use libraries and frameworks -- they replace repetitive and tedious tasks with less code. When you want to extend this functionality, you just extend the modules of the framework. Strive for maintainability. Your boss will always prefer to buy more servers than hire more programmers, it's cheaper and less paperwork. – Glitch Desire Sep 26 '13 at 07:11
  • @Starsong: He's not going to give in, it would seem... Let's change the tune: _Write your code in [assembly](http://en.wikipedia.org/wiki/Assembly_language). You can customize everything yourself, no reason why you should let some idiotic compiler decide what you want your apps to be doind. Communicate directly with the machine. And don't use an IDE, use [Emacs or butterflies](http://www.andreas-wilm.com/images/real_programmers_75p.png)!_ – Elias Van Ootegem Sep 26 '13 at 07:16
  • @EliasVanOotegem I come from a C++ close-to-the-metal background, I write Assembly at work sometimes, and I use `emacs`. I'm not coming from the POV of 'performance doesn't matter', I'm coming from the POV of 'Your customer will have up to 250ms lag with your e-commerce site which you have no control over, a 2ms or 80ms execution time makes near-zero difference to them'. On web, performance isn't critical, it's either 'good enough' or 'not good enough', and any amount of optimization past 'good enough' is fruitless. – Glitch Desire Sep 26 '13 at 07:17
  • @YonnTrimoreau On the PDO note, it's slower than `mysql_` or `mysqli_` (benchmark it and ignore the cargo cult). The point of PDO is that it offers you a very friendly and easy-to-use OO interface. – Glitch Desire Sep 26 '13 at 07:25
  • @Starsong: I'm entirely on your side on this... 95% of my working hours are spent doing webdev stuff. Some of my work is writing C(++), for _time-critical operations only_. The Assembly-emacs stuff was meant for the OP. I'm not hating on Emacs, BTW (I like its tetris :-})... Oh, and yes, PDO is a tad slower, but for queries that take approx 300 ms, the difference rarely exceeds 40ms, because, at heart, they both use the same C libs... – Elias Van Ootegem Sep 26 '13 at 07:26
  • @EliasVanOotegem PDO is much slower for small ops, a little slower for large ops. My point is that it doesn't matter because any essence of time criticality on web is killed by requesting over the inherently slow Internet. Choosing a good datacenter, caching policy and CDN will do more for load speeds than any programmer in any language will. :P – Glitch Desire Sep 26 '13 at 07:30
  • 1
    @Starsong: Yes, I never disagreed with you on any of these things :P. I have added a recap to my answer though, I included the assembly and emacs remarks, but it's mainly about maintainable code, and open-source – Elias Van Ootegem Sep 26 '13 at 07:40
  • Thanks for helping a young developer as I was ;) Time flies ! – Yonn Trimoreau Jul 04 '18 at 13:32