簡體   English   中英

cakephp控制器的全局變量

[英]cakephp global variable for controllers

我正在嘗試更改數據庫連接,具體取決於誰正在嘗試登錄我的頁面。

我需要的是一種保存正確的數據庫名稱的方式,以便所有我的控制器都可以訪問它。

使用會話可以工作,但我懷疑它的安全性和/或良好做法。 如果我可以從AccountsController中在AppController中設置一個變量,那將是完美的。 但基本上任何使我能夠在所有控制器之間共享變量的方式。

在我的AccountsController中,我向標准數據庫查詢正確的名稱。 然后我使用configure::write('CompanyDB', $myDbVar) 這對於此控制器來說可以正常工作,但是我不能在任何其他控制器中使用configure::read('CompanyDB')

在我的AppModel中,我有一個構造函數,該函數根據前面提到的configure::read('campanyDB')的值設置數據庫連接,我需要在所有我的configure::write('CompanyDB',$myDbVar)使用configure::write('CompanyDB',$myDbVar)控制器為此工作。

在我的帳戶模型中,我設置了$specific=true 這告訴AppModel應該使用該構造並更改db連接。

class AccountsController extends AppController {

    public $helpers = array('Html', 'Form','Js');
    public $components = array('RequestHandler');
    var $uses = array('User', 'Company');
    public $name = 'Accounts';
    public $myDbVar='coolbeans';

    public function beforeFilter() {
        parent::beforeFilter();
        Configure::write( 'companyDB',$this->myDbVar);
    }   
}

class AppModel extends Model {
    var $specific = false;
    function __construct($id = false, $table = null, $ds = null) {
        if ($this->specific) {
            // Get saved company/database name
            $dbName = Configure::read('companyDB');
            // Get common company-specific config (default settings in database.php)
            $config = ConnectionManager::getDataSource('companySpecific')->config;
            // Set correct database name
            $config['database'] = $dbName;
            // Add new config to registry                 
            ConnectionManager::drop('companySpecific');
            ConnectionManager::create('companySpecific', $config);
            // Point model to new config
            $this->useDbConfig = 'companySpecific';
        }
        parent::__construct($id, $table, $ds);
    }
}

class Account extends AppModel {

    public $primaryKey = '_id';
    //var $useDbConfig = 'mongo';
    var $specific = true;
    .....
}

最好的選擇是使用配置文件:

讀寫配置文件: http : //book.cakephp.org/2.0/en/development/configuration.html#reading-and-writing-configuration-files

基本思想是,在Config/目錄中創建一個具有應用程序設置的文件,然后在引導程序中加載該配置文件,這將使這些變量中的任何一個在應用程序中的任何位置可用。

示例文件: Config/dbconnections.php

<?php
$config = array(
    'MyAppDBs' => array(
        'company1' => 'connectionName',
        'company2' => 'differentConnectionName
    )
);

在您的引導文件中:

Configure::load('dbconnections');

您應用中的任何位置:

$whatever = Configure::read('MyAppDBs.companyDB');

我想如果你這樣做

configure::write('CompanyDB', $myDbVar);

在您的appController中,然后您可以使用

configure::write('CompanyDB',$myDbVar);

因為所有控制器都繼承了appController。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM