2

I'm rewriting my application to make use of CodeIgniter. Currently I'm struggling with DB. I've configured databases in config/databases.php but have no idea how to access them at a library level.

I'm loading libraries via autoload.php:

$autoload['libraries'] = array('database', 'FGMembersite', 'phpmailer', 'formvalidator');

FGMembersite is a class which I'm using for registration and login.
I access this class in login.php view where I have:

if(isset($_POST['submitted']))
{
   if($this->fgmembersite->Login())
   {
        $this->fgmembersite->RedirectToURL("main");
   }
}

fgmembersite->Login() leads to:

public function DBLogin()
{

  $this->connection = pg_connect("host=localhost port=5432 dbname=".$this->db->database." user=".$this->ci->db->username." password=".$this->db->password."");

but DBLogin() here doesn't understand what is db . I receive errors like
Undefined property: FGMembersite::$db
or
Trying to get property of non-object

How I'm supposed to access database config in my FGMembersite?

4

1 回答 1

2

您需要使用CodeIgniter 超级对象从其他库中访问自动加载的库。像这样

$ci =& get_instance();

$this->connection = pg_connect("host=localhost port=5432 dbname=" . $ci->db->database . 
                               " user=" . $ci->db->username . 
                               " password=" . $ci->db->password );

看起来您试图在代码中使用此方法,但您仅将它用于username字段,而不是databaseand password

您可以通过将 ci 实例分配给类构造函数中的类属性来保存 ci 实例,如下所示:

class Yourclass {

    private $ci;

    public function __construct() {

        $this->ci =& get_instance();  

    }

    public DBLogin() {

         $this->connection = pg_connect("host=localhost port=5432 dbname=" .
                             $this->ci->db->database . 
                               " user=" . $this->ci->db->username . 
                               " password=" . $this->ci->db->password );
    }

    public somethingElse() {

        print_r ($this->ci->db->username);

    }

}
于 2013-10-17T15:17:27.390 回答