2014-11-01 67 views
0

我使用Codeigniter与动态子域,但在我的控制器的每种方法中,我需要获取动态子域的帐户。我正在寻找一种方式来获得域和不加个$数据,它像每一个方法:Codeigniter子域通配符获取帐户的每种方法

<?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); 
    } 
} 

回答

2

一个Class Constructor内做一次,然后就可以从所有其他的访问相同的变量方法。

As per docs

“构造函数是如果你需要设置一些默认值,或运行时,你的类实例化一个默认的构造函数的过程不能返回值是有用的,但他们可以做一些默认的工作。“

<?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); 
    } 

} 

注:即使笨功能的默认设置为“公开”,这是对他们宣布这样的最佳实践。请参阅:Public functions vs Functions in CodeIgniter

+0

有一些方法可以创建我的自定义控制器并从我的控制器扩展所有,以隐藏构造函数方法,以获取帐户数据? – cristianormoraes 2014-11-02 01:40:42

+0

@cristianormoraes,我不明白你的评论的语法或措辞。 – Sparky 2014-11-02 01:41:32