Im having a hard time grasping this concepts of objects and how they should interact/exist.
Should I for instance have different objects (well, maybee I mean connections to the database here if there is any difference) for interactions with my database whenever they are not related?
Lets say I have one object that index.php uses to get and display content from the database
and another object that a user use to add/remove things in the database. We can say that the objects are all of the class dbinteract which holds all the functions for messing about with the database.
Or should I maybee divide the classes into something like: dbconnection, dbdisplay, dbinsertion, dbmodification where I send the dbconnection to the other objects?
I feel like im missing something very obvious and it’s frustrating trying to move forward not knowing where in the thought process im going wrong, I guess im looking for a question as well as a an answer here.
index.php
$connection = new dbconnection();
$displayer = new dbdisplay();
$activeconnection = $connection->connecttodatabase();
$pagetodisplay = $connection->getcontentofpagetodisplay($query);
$displayer->displayPage($activeconnection, $pagetodisplay);
userinsert.php
$inserter = new dbinsert();
$usersdbconnection = new dbconnection();
$inserter->newPost($userdbconnection, $usercredentials, $posttextfromuser);
$usersdbconnection->closedatabaseconnection();
You seem to be think at the wrong level of abstraction. OOP allows you to think about ‘users’ and ‘articles’ instead of ‘database connections’ and ‘pages’.
I’m not sure I understand the problem fully – I think your question is ‘which object should be responsible for connecting to the database?’. Creating a connection to the database only needs to be done once. This connection can then be shared between all of the objects. To share the connection you will need to create a class which all other classes that connect to the database can inherit from and a
staticvariable in that class to ensure that only one connection object exists.In other languages
staticvariables are commonly calledclassvariables.