首页 > 程序开发 > ZF1.8 快速上手

ZF1.8 快速上手

2009年7月30日

ZF有段时间没有弄了,自从ZF1.8出来之后改动比较大,把一些东西整理一下,温故而知新。

首先是下载ZendFramework,由于ZF的版本更新很快,一些小版本基本是2周出一次下载最新的ZF,下载后将ZF放到系统类库目录,我们假设是/usr/local/lib/,

其次,将ZF添加到系统目录中去,可以修改php.ini(如果不确定php.ini所在目录,可以通过phpinfo查看),在include_path中增加如下目录:include_path=”.:/path/to/zf:/usr/share/php:/usr/share/pear”,对于以ZF为主的系统,将ZF包含目录放在最前面有助提高效率,详细请看这篇文章。在进行下一步之前,我们需要先确定目录构造,请参见ZF所推荐的Zend Framework的目录结构

开始工作,首先index.php比较简单:

<?php

// Define path to application directory
defined('APPLICATION_PATH')
 || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// Define application environment
defined('APPLICATION_ENV')
 || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
 realpath(APPLICATION_PATH . '/../library'),
 get_include_path(),
)));

/** Zend_Application */
require_once 'Zend/Application.php';  

// Create application, bootstrap, and run
$application = new Zend_Application(
 APPLICATION_ENV,
 APPLICATION_PATH . '/configs/config.ini'
);

$application->bootstrap()
 ->run();

接下来是bootstrap.php我最开始写ZF的时候最麻烦的部分就是bootstrap,花了不少时间调试。Bootstrap,顾名思义就是系鞋带,指出发之前做的准备工作。自从Zend Framework 1.8以后,ZF出了Zend_tool和Zend_Application,因此Bootstrap有了比较大的调整,基本来讲,只需要在index.php中调用Zend_Application,就可以直接免去过去设定config文件,DB,view等。如果需要对这些做特别设置,可以在Bootstrap中扩展Zend_Application_Bootstrap_Bootstrap,用_init*资源函数来设定,BootStrap将依顺序逐个调用这些_init*资源函数,然后执行dispatch。用这里有篇是介绍如何将老的Bootstrap迁移到ZF1.8上。需要注意的有几点,

1.  在initView的时候尽量不要标注Response属性,这样这个Bootstrap不会在layout之前实例化Response;

2.  可以判断ajax的request头,用以去除layout, ViewRender,errorHandler和Exception的输出,这样就免除在ajax页面里面单独进行设定了。

3. ZF1.8之后可以通过设定driver option的方式对ZF的DB charset进行lazy load方式的设定了。

<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
 protected $_config;
 protected $_cache;
 protected $_requesttype;

 public function run() {
 $frontController = Zend_Controller_Front::getInstance();
 $frontController->dispatch();
 }

 protected function _initAutoload(){
 $autoloader = new Zend_Application_Module_Autoloader(array(
 'namespace' => '',
 'basePath'  => APPLICATION_PATH,
 ));
 return $autoloader;
 }

 protected function _initConfig(){
 // config
 $this->_config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/config.ini', APPLICATION_ENV);
 Zend_Registry::set('config', $this->_config);
 Zend_Registry::set('env', APPLICATION_ENV);

 //Load Application Level configure
 $appconf = new Zend_Config_Ini(APPLICATION_PATH . '/configs/app.conf', APPLICATION_ENV);
 Zend_Registry::set('appconf', $appconf);

 if (1 == (int)$this->_config->debug->showpageinfo){
 Zend_Registry::set('PageStartTime', microtime(true));
 }
 }

 protected function _initDB(){
 if($this->_config->db) {
 $db = Zend_Db::factory($this->_config->db);
 if($this->_config->cache->tablemeta && isset($this->_cache)) //setup Metacache to speed up
 Zend_Db_Table::setDefaultMetadataCache($this->_cache);
 Zend_Db_Table_Abstract::setDefaultAdapter($db);
 Zend_Registry::set('db', $db);
 }
 }

 protected function _initView(){
 // view and layout setup
 $view = new Zend_View(array('encoding'=>'UTF-8'));
 $view->addHelperPath(APPLICATION_PATH.'/default/views/helpers/');
 //$viewRendered = new Zend_Controller_Action_Helper_ViewRenderer($view);
 //Zend_Controller_Action_HelperBroker::addHelper($viewRendered);

 Zend_Dojo::enableView($view);
 $view->dojo()->setDjConfigOption('parseOnLoad', true)
 ->requireModule('dijit.form.FilteringSelect')
 ->requireModule('custom.PairedStore');
 //$view->addBasePath(realpath('./templates/default/'));

 //if ajax submit
 if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
 $this->_requesttype="ajax";
 }else{
 $this->_requesttype="html";
 Zend_Layout::startMvc(array(
 'layoutPath'=>APPLICATION_PATH . '/layouts',
 'layout'=>'layout'
 ));
 }
 $view->doctype('XHTML1_STRICT');
 Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setView($view);
 }

 protected function _initFrontController(){
 $frontController = Zend_Controller_Front::getInstance();
 $frontController->setControllerDirectory(APPLICATION_PATH .'/controllers');
 $frontController->setParam('env', APPLICATION_ENV);
 if ("ajax" == $this->_requesttype){
 // Disable the ErrorHandler plugin
 $frontController->setParam('noErrorHandler', true);
 // Disable the ViewRenderer helper
 $frontController->setParam('noViewRenderer', true);
 }
 $frontController->throwExceptions(false);
 $frontController->setBaseUrl('/');
 // action helpers
 Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH .'/controllers/helpers');
 }

 protected function _initSession(){
 if (isset($this->_config->session)){
 $session = $this->_config->session;
 if (empty($session->save_path))
 $session->save_path = APPLICATION_PATH. "/../data/sessions/";
 }
 Zend_Session::setOptions($this->_config->session->toarray());
 }

 protected function _initCache(){
 /**
 * Setup Core Cache
 */
 if ('true' == $this->_config->cache->caching){
 $CacheFrontendOptions = array(
 'lifeTime' => $this->_config->cache->lifetime,  // cache lifetime of half a minute
 'caching' => $this->_config->cache->caching,
 'automatic_serialization' => $this->_config->cache->automatic_serialization,  // this is default anyway
 'automatic_cleaning_factor'=>$this->_config->cache->automatic_cleaning_factor,
 'logging' => $this->_config->cache->logging,
 );
 switch($this->_config->cache->backend){
 case 'memcached':
 $MemcachedBackendOptions = array(
 'servers'=>array(array(
 'host' => $this->_config->cache->memcached->host,
 'port' => $this->_config->cache->memcached->port,
 'persistent' => $this->_config->cache->memcached->persistent
 )));
 $this->_cache = Zend_Cache::factory('Core', 'Memcached', $CacheFrontendOptions, $MemcachedBackendOptions);
 break;
 case 'file':
 default:
 $FileBackendOptions = array(
 'cache_dir' => APPLICATION_PATH.'/../data/cache/',
 'read_control'=>true,
 'read_control_type'=>'md5',
 'hashed_directory_level'=>'1'
 );
 $this->_cache = Zend_Cache::factory('Core', 'File', $CacheFrontendOptions, $FileBackendOptions);
 break;
 }//End of switch
 Zend_Registry::set('cache', $this->_cache);
 }
 /**
 * Setup Page cache
 */
 if($this->_config->cache->page->caching){
 $pageCacheRegexpsConfig = array(
 'cache_with_get_variables'=>true,
 'cache_with_post_variables'=>true,
 'cache_with_session_variables'=>true,
 'cache_with_files_variables'=>true,
 'cache_with_cookie_variables'=>true,);
 $pageCacheFrontendOptions = array(
 'lifetime' => $this->_config->cache->lifetime,
 'debug_header' => $this->_config->cache->page->debug, // for debugging
 'regexps' => array(
 // cache the whole IndexController
 '^(.+)-lc-(.*).html' => array_merge($pageCacheRegexpsConfig,array('tags'=>array('lc'))),
 )
 );

 if (empty($FileBackendOptions)){
 $FileBackendOptions = array(
 'cache_dir' => APPLICATION_PATH.'/../data/cache/',
 'read_control'=>true,
 'read_control_type'=>'md5',
 'hashed_directory_level'=>'1'
 );
 }

 // getting a Zend_Cache_Frontend_Page object
 $page_cache = Zend_Cache::factory('Page',
 'File',
 $pageCacheFrontendOptions,
 $FileBackendOptions);
 $page_cache->start();
 }
 }

 protected function _initTranslation(){
 //Setup Locale
 Zend_Locale::setDefault('en');   //fallback locale
 $locale = new Zend_Locale('auto'); //auto detection for user locale
 if (isset($this->_cache)) Zend_Locale::setCache($this->_cache); //cache locale to speed up
 Zend_Registry::set('Zend_Locale', $locale); //set up application-wide locale
 //Setup Zend Translate

 //$this->_cache = Zend_Cache::factory('Page','File',$frontendOptions,$backendOptions);
 //Zend_Translate::setCache($this->_cache);
 $translate = new Zend_Translate('gettext','../data/locales/',NULL,array(
 'scan' =>Zend_Translate::LOCALE_DIRECTORY,
 'disableNotices' => true
 ));
 Zend_Registry::set('Zend_Translate', $translate);
 //Zend_Validate_Abstract::setDefaultTranslator($translate);
 Zend_Form::setDefaultTranslator($translate);
 }

 protected function _initRoutes(){
 //$router = new Zend_Controller_Router_Rewrite();
 //$router->addConfig($appconf, 'routes');
 }
}
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

程序开发

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.

This blog is kept spam free by WP-SpamFree.