Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJoey L.
4,601 PointsRandy 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 :)
1 Answer
Yousuf Tafhim
8,402 PointsAs 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 :)
Joey L.
4,601 PointsJoey L.
4,601 PointsThank you buddy. I got confused because there was no other function that would call it and I had initially assumed we would be modifying the function to run different queries based on an input argument. It became clear in the following chapter that we'd be making different functions. I don't know why I hadn't seen that ahead.
Cheers for your reply though mate, all the best!