Skip in the connection object or create it inside the class? (OOP)

I have a class that handles several database operations. I want the class to be as convenient and well thought out as possible, and I'm pretty new to OOP, so I would appreciate a solution to this:

Is it better to do this:

class MyDatabase extends Database { private $connection; public function __construct(mysqli $connection) { $this->connection=$connection; } //More functions below } 

or

 class MyDatabase extends Database { private $connection; public function __construct() { $this->connection=new mysqli(...); } //More functions below } 

What are the pros and cons of both, and which one is used more often? I cannot decide for whom I should start using, and this will affect the rest of the application that I am writing.

thanks

+4
source share
2 answers

I would suggest the first one, without a hard-coded dependency, is testable and can change the object connection at any time. I highly recommend you watch this .

+1
source

I would suggest a second approach, especially if you are new to OOP.

The key principle in OO is "hiding information", you want to hide as much information as possible inside the class, so as not to expose complexity from the outside.

The advantage of the second approach is that it completely hides all the details of working with the database, since the constructor does not accept any parameters.

Sometimes the first approach is preferable in a larger and more complex system, where your class "MyDatabase" should be able to handle different types of basic database connections and should probably use different types of connections in its constructor. But this is another design in which we disclose the details of the database descriptor and essentially include this as part of the API (the so-called contract in OO terms) in the outside world.

Another common OO practice is frequent refactoring. If you have a good development environment and good enough programming practice, you can quite easily reorganize your code from a simpler approach (No. 2) to a more complex one (No. 1) without any problems. So I say go ahead with C # 2, keep it simple and refactor along the way when necessary.

In terms of performance, I see a slight difference in the two approaches, you can (and should) always use persistent connections anyway. Thus, the service data of the object should be minimal.

0
source

Source: https://habr.com/ru/post/1502321/


All Articles