一種方法是將屬性添加到任何控制器,將需要數據的sysConfig
。變量的名稱不應該是$ config,因爲CI已經使用該符號 - 它由Config
類定義和設置。所以對於這個答案我會用$sysConfig
。
class Some_controller extends CI_Controller
{
protected $sysConfig; //class property with scope to this controller
public function __construct()
{
parent :: __construct();
$this->load->model('sysConfig_model');
}
sysConfig_model
(未顯示)管理您似乎已建立的表格。由於您沒有向我們展示任何代碼,因此我正在爲該模型編寫函數。模型功能get($id)
根據$id
檢索所需的「用戶」,並返回數組中的數據。 ($id
的設定值沒有顯示。)
控制器可以按照需要通過$this->sysConfig
使用該屬性,就像在這個公認的微不足道的控制器功能中一樣。
類定義繼續...
public function format_title()
{
if(isset($this->sysConfig){
$this->sysConfig['suckup'] = "the most highly regarded "
. $this->sysConfig['title']
. " in the world visit our site!";
}
}
其實對於$this->sysConfig
分配一個值發生在這個代碼下位。在此示例中,控制器的index()
函數可以接收一個參數,該參數是我們想要從數據庫中獲取的用戶的「ID」。
public function index($id = NULL)
{
//assign data to the class property $sysConfig from the model
$this->sysConfig = $this->sysConfig_model->get($id);
該屬性可以很容易地傳遞給視圖。首先我們做一些吸吮。
$this->format_title();
$data['userStuff'] = $this->sysConfig;
$this->load->view('some_view', $data);
} //end of index()
} //end of class Some_controller
some_view.php
<div>
<h4>Welcome <?php echo $userStuff['firstName']. " " . $userStuff['lastName']; ?></h4>
<p>I cannot say how swell it is to have <?php echo $userStuff['suckup']; ?></p>
</div>
的 「全球性」 的想法實在是違背OOP方法在PHP - 或任何其他OOP語言。
在提出任何問題之前請閱讀文檔。例如,你可以通過這個http://www.codeigniter.com/userguide3/database/results.html –
@ sayantan-das我可以從數據庫中選擇任何數據,我沒有任何問題。我想在名爲$ Config的變量中選擇表sysConfig上的數據並直接訪問它。 – 56356356356
然後,你可以添加一個幫助文件,並在幫助器中寫入一個函數,如'getConfig('config_name_here')',它將檢索請求的配置值。現在,如果你自動加載你的自定義幫助器,該幫助器中的所有功能都可用在整個項目中。你可以像訪問它一樣,<?= getConfig('config_name')?> –