A
A
Artem2015-07-29 22:21:12
PHP
Artem, 2015-07-29 22:21:12

What is the correct way to use $bd in OOP?

Hello!
I am writing an API that will be used by a client desktop application. But the question is general, according to OOP.
I use the Fat-Free framework.
In index.php, it connects like this:
$f3 = require('lib/base.php');
And it connects to the database like this:

$db = new DB\Mongo($f3->get('dbhost'),$f3->get('dbname'));

In order not to write the entire API in one file, I want to make several modules, each module has its own class. After all, in the API, all the work is tied to the database.
The question arises: how to pass the $f3 and $db object to each module, and use them in class objects?
Transmit continuously like this:
class MyClass {
  public $f3;
  function __construct($f3) {
    $this->f3=$f3;
  }		
  function MyFunc() {			
    $this->f3->somebody();
  }
}

$obj= new MyClass ($f3);

In my opinion, not very rational. I would like to create these objects once, and not pass them to objects of other classes, but use them inside these objects. Is it possible?
How is this implemented in various engines, CMS? How do you write?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Anton Tikhomirov, 2015-07-30
@ber_enot

Everything is simple. You're a bit confused about scopes)

class MyClass {
  
  private $f3, $db;
  
  function __construct () {
    global $f3, $db;
   
    $this->f3 = $f3;
    $this->db = $db;
    
  }
  
  function MyFunc () {
    $this->f3->somebody ();
  }
  
}

$obj = new MyClass ();

O
OnYourLips, 2015-07-29
@OnYourLips

Try the DI pattern, here is a very simple library: pimple.sensiolabs.org You
describe the dependencies of all classes, and she creates them herself.

W
wol_fi, 2015-07-29
@wol_fi

Registry, Dependency Injection, Singleton (now they will start throwing poop) - choose any pattern.

B
Boris Lapin, 2015-07-29
@MrBoriska

There is such a thing as a singleton. An example can be viewed here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question