我将Codeigniter与动态子域一起使用,但在我的控制器的每个方法中,我需要获取动态子域的帐户。我正在寻找一种方法来获取域并添加到$ data,而不是每个方法,如:
<?php
class Dashboard extends CI_Controller {
function index()
{
$subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2);
$subdomain_name = $subdomain_arr[0];
$this->db->from('accounts')->where('subdomain', $subdomain_name);
$query = $this->db->get();
$account = $query->row();
$data['account_id'] = $account->id;
$data['account_name'] = $account->name;
$this->load->view('index', $data);
}
function clients()
{
$subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2);
$subdomain_name = $subdomain_arr[0];
$this->db->from('accounts')->where('subdomain', $subdomain_name);
$query = $this->db->get();
$account = $query->row();
$data['account_id'] = $account->id;
$data['account_name'] = $account->name;
$this->load->view('clients', $data);
}
}
答案 0 :(得分:2)
在Class Constructor内执行一次,然后您可以从所有其他方法访问相同的变量。
“如果你需要设置一些默认值,那么构造函数很有用,或者在实例化类时运行默认进程。构造函数不能返回值,但是他们可以做一些默认工作。“
<?php
class Dashboard extends CI_Controller {
public $data = array();
public function __construct()
{
parent::__construct();
$subdomain_arr = explode('.', $_SERVER['HTTP_HOST'], 2);
$subdomain_name = $subdomain_arr[0];
$this->db->from('accounts')->where('subdomain', $subdomain_name);
$query = $this->db->get();
$account = $query->row();
$this->data['account_id'] = $account->id;
$this->data['account_name'] = $account->name;
}
public function index()
{
$data = $this->data; // contains your values from the constructor above
$data['title'] = "My Index"; // also use your $data array as normal
$this->load->view('index', $data);
}
public function clients()
{
$data = $this->data; // contains your values from the constructor above
$this->load->view('clients', $data);
}
}
注意:尽管CodeIgniter函数默认为“public”,但最佳做法是将它们声明为“public”。请参阅:Public functions vs Functions in CodeIgniter