Randy included the PDO() object creation and database connection code in the same place as it initially was. Why?
How does this actually change anything? Include files are essentially pasted PHP code wherever the include/require functions are run no?
So if he included the database connection code back in the get_products_all() function before the first query, how has he actually changed anything? Wouldn't it make more sense to include it outside of the function to prevent it being run each time the function itself is run?
Please help clarify guys. Thanks :)
Yousuf Tafhim8,402 Points
As Randy mentioned, becuase of seperatioin of concerns he decided that the database connection code should be in a seperate file.
At this point in the course there are no other functions that want to query the database, so putting the database connection code in get_products_all() function or having it on a separate file doesnt makes any difference.
Let's say in the future we add a "size" table in the database and we make a function get_all_sizes() function in the products.php file. As we have the database connection code in the get_products_all() function, we will copy that code to get_all_sizes() function as well. What if in the future we would want to make more functions that needs to connect to the database? This means we are duplicating code which is a bad coding practice. And you can easily identify what will happen when the database connection is changed (say a new host). We will have to make the change in every line of code where we copy-pasted the db connection code.
I hope it is clear :)