From 80e2f228b1686938a5213b6005c185199d4d842a Mon Sep 17 00:00:00 2001 From: colshrapnel Date: Thu, 9 Nov 2017 13:45:03 +0300 Subject: [PATCH] A single uniform connection instead of separate connections in the every class Connecting in every data class is a sure bad practice, and anyone who would try to extend the previously used approach to other classes will end up with tens of simultaneous connections to the database from the same PHP instance. So a database connection should be instantiated only once and then passed to all objects as a constructor parameter. Given this lesson is linked on the PHPTheRightWay, it shouldn't promote a bad practice, even for sake of simplification. --- sites/intro-to-php/creating_a_data_class.step | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/sites/intro-to-php/creating_a_data_class.step b/sites/intro-to-php/creating_a_data_class.step index ca0f83166..57570e040 100644 --- a/sites/intro-to-php/creating_a_data_class.step +++ b/sites/intro-to-php/creating_a_data_class.step @@ -20,16 +20,16 @@ steps do end step do - message "Now create a connect function:" + message "Now create a constructor that will assign a PDO instance to a class variable:" source_code :php, <<-PHP connection = new PDO("mysql:host=localhost;dbname=suggestotron", "root", "root"); + $this->connection = $pdo; } } ?> @@ -43,11 +43,11 @@ steps do connection = new PDO("mysql:host=localhost;dbname=suggestotron", "root", null); + $this->connection = $pdo; } public function getAllTopics() @@ -70,10 +70,9 @@ steps do source_code :php, <<-PHP connect(); - + $data = new TopicData($pdo); $topics = $data->getAllTopics(); PHP