08.
Making only one DB Connection with a Property
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
Whoops, an error! Please, try again later.
10 Comments
Hi !
What do you mean by
?
This trick seams to be interesting only if the object lives during the whole session, not only during a simple request.
Hey Marc R.
I don't think an object can live after the request-response cycle. That trick is useful because creating a PDO instance is expensive and it's likely that it will be used more than one time during a request
Cheers!
Hi!
You have a minor typo at the final code sample:
if ($this->pdo === null) {
$this->pdo = new PDO('mysql:host=localhost;dbname=oo_battle', 'root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
I bet it must be "$this->pdo->setAttribute" instead of "$pdo->setAttribute".
Hi Ivan,
You're absolutely right! I fixed it, but it takes a while when our cache regenerate and you will see these changes.
Thanks for noticing us!
Why not setting the $pdo property when the object is initiated using the constructor?
Hey Thrasos,
Really good question! Actually, since we don't know what is dependency injection and dependency injection container yet, it was just a simple refactoring to avoid code duplication. And the another point is that we have a lazy loading PDO instance here, since we create it *only* when the getPDO() method is called at first time. But anyways, it was just a intermediate refactoring and we will consider more cool stuff as DI Container further.
Cheers!
Thanks for the quick reply! Just a small question. Would it be a better practice (without knowing what DI is) to create a constructor method and within call a createPDO method that would initiate a PDO object and set it at a $pdo property?
Hey Thrasos,
Yes, I think so as long as you have a hard dependency with PDO object. But as we see, ShipLoader has and just won't work without PDO instance. Actually, we will do this further in the course.
Cheers!
Yes as I can see from next videos it's a bad practice to create services on a service class.
Yeah, that's why using DI Container is the best practice here.
Cheers!
"Houston: no signs of life"
Start the conversation!