2009-11-05 2 views
22

quick-start 설정을 기반으로하는 Zend Framework 응용 프로그램이 있습니다.컨트롤러에서 Zend Framework 애플리케이션의 구성에 어떻게 액세스합니까?

데모가 작동 중이며 새로운 모델 클래스를 인스턴스화하여 실제 작업을 수행하고 있습니다. 내 컨트롤러에서 나는, 나의 모델 생성자에 이런 일을합니다 (application.ini에 지정된) 구성 매개 변수를 전달하려면 :

class My_UserController extends Zend_Controller_Action 
{ 
    public function indexAction() 
    { 
     $options = $this->getFrontController()->getParam('bootstrap')->getApplication()->getOptions(); 
     $manager = new My_Model_Manager($options['my']); 
     $this->view->items = $manager->getItems(); 
    } 
} 

예 위의 옵션에 대한 액세스를 허용 않지만, 매우 라운드에 대한 보인다 . 구성에 액세스하는 더 좋은 방법이 있습니까?

답변

47

항상 다음 부트 메소드에 init 메소드를 추가하여 구성을 레지스트리로 전달합니다.

protected function _initConfig() 
{ 
    $config = new Zend_Config($this->getOptions(), true); 
    Zend_Registry::set('config', $config); 
    return $config; 
} 

이것은 당신의 코드를 약간 단축 : 허용 public 멤버 함수 대신 모든 응용 프로그램 정보를 포함하는 단일 응용 프로그램 클래스를 만들 수 Zend_Registry을 사용하는, 또는

class My_UserController extends Zend_Controller_Action 
{ 
    public function indexAction() 
    { 
     $manager = new My_Model_Manager(Zend_Registry::get('config')->my); 
     $this->view->items = $manager->getItems(); 
    } 
} 
+0

개체를 다시 구문 분석하는 데 약간의 시간이 걸립니다. 설정을 배열로 갖는 것을 선호한다면, 그것은 단지 "Zend_Registry :: set ('config', $ this-> getOptions());"입니다. 값을 얻기 전에 변수로 가져와야합니다. –

+0

@Alister : 맞습니다. 옵션 배열을 레지스트리에 저장하는 것이 더 빠를 것입니다. 그러나 단일 값을 가져올 때마다 배열을 저장하는 것은 번거로울 수 있습니다. –

+2

이것은 아래 $ GLOBALS [ 'application'] 아이디어와 다르지 않으며 $ GLOBALS [ 'application']이 아마 99 %의 시간 동안 작동한다는 이점이 있습니다. –

6

을 관련 데이터에 액세스 할 수 있습니다. 당신이 관련 코드와 조각을 발견하실 수 있습니다 (그것은 단지 당신이 구현할 수있는 방법을 알 수 있도록, 그대로 실행되지 않습니다) :

final class Application 
{ 
    /** 
    * @var Zend_Config 
    */  
    private $config = null; 

    /** 
    * @var Application 
    */  
    private static $application; 

    // snip 

    /** 
    * @return Zend_Config 
    */ 
    public function getConfig() 
    { 
     if (!$this->config instanceof Zend_Config) { 
      $this->initConfig(); 
     } 
     return $this->config; 
    } 

    /** 
    * @return Application 
    */ 
    public static function getInstance() 
    { 
     if (self::$application === null) { 
      self::$application = new Application(); 
     } 
     return self::$application; 
    } 

    /** 
    * Load Configuration 
    */ 
    private function initConfig() 
    { 
     $configFile = $this->appDir . '/config/application.xml'; 
     if (!is_readable($configFile)) { 
      throw new Application_Exception('Config file "' . $configFile . '" is not readable'); 
     } 
     $config = new Zend_Config_Xml($configFile, 'test'); 
     $this->config = $config; 
    } 

    // snip 

    /** 
    * @param string $appDir 
    */ 
    public function init($appDir) 
    { 
     $this->appDir = $appDir; 
     $this->initConfig(); 
     // snip 
    } 

    public function run ($appDir) 
    { 
     $this->init($appDir); 
     $front = $this->initController(); 
     $front->dispatch();    
    } 
} 

부트 스트랩은 다음과 같이 보일 것이다 :

require 'Application.php'; 
try { 
    Application::getInstance()->run(dirname(dirname(__FILE__))); 
} catch (Exception $e) { 
    header("HTTP/1.x 500 Internal Server Error"); 
    trigger_error('Application Error : '.$e->getMessage(), E_USER_ERROR); 
} 
구성을 액세스 할 때

는 다음을 사용합니다

$var = Application::getInstance()->getConfig()->somevar; 
0

나는 부트 스트랩의 시작 부분에서 나는 require_once를 어떤 장소()에서 짧은 손을 정의했습니다 :

function reg($name, $value=null) { 
    (null===$value) || Zend_Registry::set($name, $value); 
    return Zend_Registry::get($name); 
} 

및 부트 스트랩에서 나는이 :

가장 ZF 응용 프로그램에서
$app = reg('::app'); 
3

, 응용 프로그램 개체가 선언되어 그때를 사용하여 어디에서나 응용 프로그램 인스턴스를 얻을 수

protected function _initFinal() 
{ 
    reg('::app', $this->getApplication()); 
} 

을 전역 범위 (ZFW_DISTRIBUTION/bin/zf.sh로 생성 된 앱의 public/index.php 참조)

정확하게 ZF 방식이 아니지만 $GLOBALS['application']으로 개체에 액세스 할 수 있습니다. 일종의 속임수로 느껴지 긴하지만, 공연이 끝나면 가장 빠른 옵션 일 것입니다.

$manager = new My_Model_Manager($GLOBALS['application']->getOption('my')); 
+1

프레임 워크와 모든 추상화를 우회하는 것이 항상 가능합니다. 이와 같은 솔루션은 가야할 해결책이 아닌 완전히 실패한 해킹이어야합니다. 어떤 경우에도 성능이 중요하지는 않습니다. 구성 변수는 성능이 중요한 루프 내에서 페치 될 필요가 없습니다. –

+0

My_Model_Manager이란 무엇입니까 ?? – zardilior

+0

@ zardilior 가장 좋은 추측 (4 년 후)은 가설적인 사용자 정의 옵션 인 'my'에 의존하는 가설적인 사용자 영역 클래스라는 것입니다. 이들 두 가지 모두가 SO 질문에서 따왔다. ;-) –

21

버전 1.8 이후로 당신이 당신의 컨트롤러에 아래의 코드를 사용할 수 있습니다

$my = $this->getInvokeArg('bootstrap')->getOption('my'); 
1
$this->getInvokeArg('bootstrap')->getOptions(); 
// or 

$configDb = $this->getInvokeArg('bootstrap')->getOption('db'); 
0

정말 간단한 방법을 직접 액세스하여 구성 옵션입니다 액세스하기 위해 전 세계적으로 $ 응용 프로그램을 정의 변하기 쉬운.

class My_UserController extends Zend_Controller_Action { 
    public function indexAction() { 
     global $application; 
     $options = $application->getOptions(); 
    } 
}