2009-05-14 3 views
2
public function init(){ 
     $this->view->user = Zend_Auth::getInstance()->getIdentity(); 
     $this->view->siteName = Zend_Registry::get('config')->site->name; 
     $this->view->menu = $this->_helper->generateMenu(Zend_Auth::getInstance()->getIdentity()); 
     $this->view->slogan = Zend_Registry::get('config')->site->slogan; 
    } 

이것은 모든 모듈의 모든 컨트롤러에있는 init 파일입니다.이 코드를 넣을 수있는 곳은 모듈/컨트롤러를 불문하고 모든 요청을 실행합니다.모든 컨트롤러에서 init 함수의 코드를 중앙화하려면 어떻게합니까?

답변

3

당신은 Zend_Controller_Action에는을 확장 할 수 있습니다 :

public class My_Controller_Action extends Zend_Controller_Action 
{ 
    public function init() 
    { 
     $this->view->user = Zend_Auth::getInstance()->getIdentity(); 
     $this->view->siteName = Zend_Registry::get('config')->site->name; 
     $this->view->menu = $this->_helper->generateMenu(Zend_Auth::getInstance()->getIdentity()); 
     $this->view->slogan = Zend_Registry::get('config')->site->slogan; 
    } 

} 

그런 다음 당신은 그냥 아니라 Zend_Controller_Action에는보다 My_Controller_Action을 확장 할 컨트롤러를 변경합니다. 그냥뿐만 아니라) 당신이 컨트롤러의 init 메소드에 코드를 추가해야하는 경우, 당신은 부모 :: 초기화를 (호출해야합니다 것을 명심 :

내가 오히려 조언을 줄
public class FooController extends My_Controller_Action 
{ 
    public function init() 
    { 
     parent::init(); 

     // Do something. 
    } 

    public function IndexAction() 
    { 
     // ... 
    } 
} 
7

작성 Zend_Controller_Plugin_Abstract를 확장하여 플러그인으로 사용하는 것이 그 목적입니다.

이렇게하면 컨트롤러에서 아무 것도 할 필요가 없습니다. 컨트롤러를 통해 코드를 공유하기 위해

$this->_front->registerPlugin(new My_Controller_Plugin_Layout()); 

http://framework.zend.com/manual/en/zend.controller.plugins.html

4

그런 다음 당신은 행동을 만들고, 당신의 bootstrap.php에 ... 데이터에 다음

class My_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract 
{ 
    protected $_auth = null; 

    protected $_acl = null; 

    public function __construct (Zend_Auth $auth, Zend_Acl $acl) 
    { 
     $this->_auth = $auth; 
     $this->_acl = $acl; 
    } 

    public function preDispatch(Zend_Controller_Request_Abstract $request) 
    { 
     //some code 
    } 
} 

그리고 액세스하기 위해 레지스트리를 사용할 수 있습니다 당신이 가진 문제를 해결하기 위해 주로 설계된 도우미.

그들은 "요구에"실행할 수 있습니다

:

$myHelper = $this->_helper->MyHelper; 
$myHelper->someFunction(); 

도는 디스패치 프로세스가 자동으로 호출 후크의 집합을 가지고있다. 후크를 사용하려면 브로커와 액션 도우미를 등록해야합니다

$helper = new App_Controller_Action_Helper(); 
Zend_Controller_Action_HelperBroker::addHelper($helper); 

가능한 후크는 다음과 같습니다

  • init()
  • preDispatch()
  • postDispatch()

들어 자세한 내용은 매뉴얼 페이지 http://framework.zend.com/manual/en/zend.controller.actionhelpers.html에서 찾을 수 있습니다. 나는 그들에 관한 몇 가지 기사를 썼다 : http://akrabat.com/2008/10/31/using-action-helpers-in-zend-framework/http://akrabat.com/2008/11/05/hooks-in-action-helpers/