Flourish PHP Unframework
This is an archived copy of the forum for reference purposes

fDatabase connection in class

posted by jmtucu 8 years ago

Hello! I have created a connection $db = fDatabase(...) and I need to use $db in a class to run a complex query. I have to pass the connection as a parameter or is there another way to recognized the $db?

class Usuario extends fActiveRecord
{
  protected function configure()
  {
  }
  
  public function readData()
  {
    $data = $db->query(...);
    return $data;
  }
}

Should be public function readData($db) ?

Thanks!

Why not pass $db via the constructor and set it as a class variable?

class test {

   public function __construct($db)
   {
      $this->db = $db;
   }
}
posted by earth 8 years ago

Sounds good, but how can I do it if I'm using the ORM:

// login.php
$usuario = new Usuario(array('username' => 'juanma'));
$data = $usuario->readData();

// Usuario.php
class Usuario extends fActiveRecord
{
  public function __construct($db)
  {
     $this->db = $db;
  }

  public function readData()
  {
    $data = $this->db->query(...);
    return $data;
  }
}

Thanks in advanced!

posted by jmtucu 8 years ago

Inside of the ORM you can retrieve the appropriate database object by calling fORMDatabase::retrieve(). You should pass the class name you are retrieving for as the first parameter in case you every use more than one database to power your ORM.

class Usuario extends fActiveRecord
{
  protected function configure()
  {
  }
  
  public function readData()
  {
    $db = fORMDatabase::retrieve(__CLASS__);
    $data = $db->query(...);
    return $data;
  }
}
posted by wbond 8 years ago

It works perfect! You're the best, I'm going to donate very soon, I love this project :)

Thanks again!

posted by jmtucu 8 years ago