Reputation: 115
I'm thinking of creating a global variable $PDO
to use along with my script inside classes , functions and my code .
So is there any security breach can occur upon this ?
I'm now using a seperate connection every time . shall I stick with this or use global PDO object ?
Upvotes: 1
Views: 85
Reputation: 71384
This really depends on your application, as there could be cases where you want to manage multiple connections. However, in many cases, it makes sense to only open a single connection for use during the course of processing a single request. The helps eliminate the overhead of opening/closing connections throughout the code. I would guess that security would not be much of a concern in most cases unless you are planning on handing off the DB connection to a set of code that should not have the DB permissions associated with that specific connection (maybe a library or service that you do not control).
I would also highly suggest you look into the concept of dependency injection, as in most cases it would be preferable to pass around the instantiated DB object to pieces of code that need it rather than to treat it as a global and just use global
keyword to access it. This helps you avoid needing to replicate code in every class/function to check that the DB has a connection and such. If you have a single class which does this and you can pass that object around to classes that need it, they can be guaranteed that the object will do what it is supposed to do.
Upvotes: 2