/    Sign up×
Community /Pin to ProfileBookmark

Database Class used in second class

So I’ve got a class called DatabaseHandler which currently has a protected function that connects and returns the connection. Nice

I also have a second class which I want to have a function called saveObject.

Currently I have mySecondClass extends DatabaseHandler

But if I return my saved object I return my database properties too.

How can I just use my database connection object itself? What am I missing?

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@NogDogOct 22.2020 — Generally I prefer to pass the DB object into the class that needs to use it.
<i>
</i>class Foo {
private $db;
public function __construct($db){ // type-hint as appropriate in your case
$this-&gt;db = $db;
}
public something() {
$this-&gt;db-&gt;query('SELCECT * FROM something');
}
}
Copy linkTweet thisAlerts:
@kiwisauthorOct 22.2020 — @NogDog#1624489

What it my __construct is making itself.

``<i>
</i>public function __construct($ID, $Name, $Value2){
$this-&gt;ID = $ID;
}<i>
</i>
``
Copy linkTweet thisAlerts:
@NogDogOct 22.2020 — It could just be one more param to the constructor. You might end up with something sort of like...
<i>
</i>class DB extends mysqli {
// lots of cool stuff
}

class Nog {
private $db;
private $id;

<i> </i>public function __construct(DB $db, $id, $name, $value) {
<i> </i> $this-&gt;$db = $db;
<i> </i> $this-&gt;$id = $id;
<i> </i> $this-&gt;populate($name, $value);
<i> </i>}

<i> </i>private function populate($name, $value) {
<i> </i> $stmt = $this-&gt;db-&gt;prepare('some query with parameter place-holders');
<i> </i> $stmt-&gt;bind_params('iss', $this-&gt;id, $name, $value);
<i> </i>}
}

$db = new DB('whatever args go here');

$nogdog = new Nog($db, 1234, 'NogDog', 'PHP');

This helps keep database responsibilities separate from whatever it is that class Nog is modeling, keeping your classes narrowly focused on what they should be concerned with (i.e. "separation of concerns" or something like that). Since it probably is not modeling a database connection, it wouldn't really make sense to have it extend a database class -- instead just _using_ a separate database object where needed.
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 3.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 10 SATS,
)...