分類彙整: ZendFramework

Zend Framework Widget

主要是因為之前用Yii 的 Widget 用的挺開心的( 除了他會每次都進一次Cycle 外)

因為用ZF沒找到有這方面相關的資訊
所以自已動手刻…..

1. 在application 下建 Titan/Base 的資料夾 ( Titan 是我想把自已寫的東西盡可能的都收在這 )
2. vim Titan/Base/Widget.php
[sourcecode language=’php’]
< ?php abstract class Titan_Base_Widget { protected $_basePath; protected $_viewBasePath; protected $_viewScriptPath; public function __construct( $array = null ) { //assign variables $this->_basePath = APPLICATION_PATH . DS . ‘widgets’;
$this->_viewBasePath = APPLICATION_PATH . DS . ‘widgets’ . DS . ‘views’;
$this->_viewScriptPath = $this->_viewBasePath . DS . ‘scripts’;
$this->_config = Zend_Registry::get( ‘config’ );

if ( !empty( $array ) )
{
foreach( $array as $key => $val )
{
$this->$key = $val;
}
}

try {
$this->preWidget();
$this->run();
$this->postWidget();
} catch ( Zend_Exception $e ) {
echo “Caught exception: ” . get_class($e) . “n”;
echo “Message: ” . $e->getMessage() . “n”;
}

}

public function render( $action )
{
include( $this->_viewScriptPath . DS . $action . DS . $action . $this->_config->resources->view->suffix );
}

protected function preWidget(){}
abstract protected function run();
protected function postWidget(){}
}
[/sourcecode]

3. 加入include_path
[sourcecode language=’php’]
realpath(APPLICATION_PATH . ‘/widgets/controllers’ ),
realpath(APPLICATION_PATH ),
[/sourcecode]

4. 在application 目錄下建 widgets/controllers, widgets/views/scripts ( views這樣的目錄結構是因為保留到時後用Zend_View的彈性 )

5. login widget controller
[sourcecode language=’php’]
< ?php class LoginWidget extends Titan_Base_Widget { protected function run() { $this->render( ‘login’ );
}
}
[/sourcecode]

6. login widget view
在 widgets/views/scripts 下建一個 login 目錄
寫一個login.phtml
[sourcecode language=’php’]
< ?= $this->okok; ?>
[/sourcecode]

7. index view
[sourcecode language=’php’]
< ?php new LoginWidget( array( 'okok' => ‘ok1ok’ ) ); ?>
[/sourcecode]

這樣就搞定了…

PS
1.
原本想用Zend_View 來實做的
不過搞了一陣子..在他的ob_start() 及 response->appendBody 花了一些時間弄了滿久的(有一些時間壓力)
整個流程還不是搞的相當懂, 在不想把整個架構弄的很醜的情況下, 目前先用這種方式實作

2. 話說我好像一陣子沒寫筆記了………………..

ZF controller init method

[cc lang=”php” tab_size=”2″ lines=”40″]public function __construct(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array())
{
$this->setRequest($request)
->setResponse($response)
->_setInvokeArgs($invokeArgs);
$this->_helper = new Zend_Controller_Action_HelperBroker($this);
$this->init();
}[/cc]

在zf 每個 controller 中
可以用function init 這個去代替__constructor (不知道這樣形容 恰不恰當)

Whenever Zend Framework instantiates a controller, the base Zend Framework class (in our case Zend_Controller_Action) has a lot of important code in the __construct() method.  It is possible to override the __construct() in your controller but it is not recommended. Instead, Zend Framework gives us the init() method. init() is the last thing called in __construct() and it is the appropriate place for us to put anything we want executed upon construction.