显示标签为“MVC”的博文。显示所有博文
显示标签为“MVC”的博文。显示所有博文

2009年4月23日星期四

Zend Framework Plugin: 不同模块(Module)使用不同的错误控制器(ErrorController)

Zend Framework 的错误控制器提供了统一的错误处理方式, 参阅 http://framework.zend.com/manual/en/zend.controller.html#zend.controller.quickstart.go.errorhandler
  当我们工作于模块方式时,常常希望不同模块使用不同的错误处理,比如 default 模块使用默认ErrorController, 后台管理模块 admin 使用 Admin_ErrorController 提供不同的布局和更详细的错误显示。

Plugin 方式为我们提供了方便的设置途径,以下 plugin 设置每个 module 使用 模块里的 ErrorController, 如果模块不提供 ErrorController 则使用默认的 ErrorController:
require_once ('Zend/Controller/Plugin/Abstract.php');
class Mezi_Controller_Plugin_ErrorControllerSelector extends Zend_Controller_Plugin_Abstract
{
    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {
        $front = Zend_Controller_Front::getInstance();

        //If the ErrorHandler plugin is not registered, bail out
        if( !($front->getPlugin('Zend_Controller_Plugin_ErrorHandler') instanceof Zend_Controller_Plugin_ErrorHandler) )
            return;

        $error = $front->getPlugin('Zend_Controller_Plugin_ErrorHandler');

        //Generate a test request to use to determine if the error controller in our module exists
        $testRequest = new Zend_Controller_Request_HTTP();
        $testRequest->setModuleName($request->getModuleName())
                    ->setControllerName($error->getErrorHandlerController())
                    ->setActionName($error->getErrorHandlerAction());

        //Does the controller even exist?
        if ($front->getDispatcher()->isDispatchable($testRequest)) {
            $error->setErrorHandlerModule($request->getModuleName());
        }
    }
}


启动时安装 plugin:
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Mezi_Controller_Plugin_ErrorControllerSelector());




Zend Framework Plugin:自适应 magic_quotes_gpc 环境

推荐关闭 php.ini 的 magic_quotes_gpc 选项,一来可以提升性能,二来可以保证得到的原始数据,Zend_Db 会自动转义数据入库。并且新版本的 php 推荐配置都是默认关闭 magic_quotes_gpc 选项。
当然某些系统打开了 magic_quotes_gpc 选项,并且你也没有足够权限去修改这个配置,这些反斜杠可能给你造成困扰,我们可以用代码抵消修改。
Zend Framework 的 plugin 提供了很好的方式来做这些事情,而不需要改动我们去参数的每段代码。

/**
* A Zend Controller Plugin dedicated to undoing the damage of magic_quotes_gpc
* in systems where it is on.
*
* @author Ken
* @version $Id:$
*/
require_once ('Zend/Controller/Plugin/Abstract.php');
class Mezi_Controller_Plugin_StripMagicQuotes extends Zend_Controller_Plugin_Abstract
{
/**
* strip all slashes off $request parameters
*
* @param Zend_Controller_Request_Abstract $request
*/
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
$params = $request->getParams();
array_walk_recursive($params, array($this , '_stripSlashes'));
$request->setParams($params);

if ($request instanceof Zend_Controller_Request_Http) {
$this->_stripSlashesGPC();
}
}

/**
* strip all slashes from GPC
*/
protected function _stripSlashesGPC()
{
array_walk_recursive($_GET, array($this , '_stripSlashes'));
array_walk_recursive($_POST, array($this , '_stripSlashes'));
array_walk_recursive($_COOKIE, array($this , '_stripSlashes'));
}

/**
* callback strip the slashes off an item in the Params array
*
* @param string $value
* @param string $key
*/
protected function _stripSlashes (&$value, $key)
{
$value = stripslashes($value);
}
}


然后启动时安装 plugin, 仅在 magic_quotes_gpc 打开时需要处理:

$front = Zend_Controller_Front::getInstance();

if (get_magic_quotes_gpc()) {
require_once 'Mezi/Controller/Plugin/StripMagicQuotes.php';
$this->_front->registerPlugin(new Mezi_Controller_Plugin_StripMagicQuotes());
}


Plugin 非常漂亮的实现了我们的需求,以前写好的代码都无须改动。

2009年2月25日星期三

Smarty and Zend_View integrantion

聚合使用 smarty

<?php
require_once ('Zend/View/Abstract.php');
class SmartyView extends Zend_View_Abstract
{
protected $_smarty;

public function __construct($config = array())
{
$this->_smarty = new Smarty();

if(!isset($config['compileDir']))
throw new Exception('compileDir is not set for '.get_class($this));
else
$this->_smarty->compile_dir = $config['compileDir'];

if(isset($config['configDir']))
$this->_smarty->config_dir = $config['configDir'];

if(isset($config['pluginsDir']))
$this->_smarty->plugins_dir[] = $config['pluginsDir'];

parent::__construct($config);
}

public function __set($key,$val)
{
parent::__set($key, $val);
$this->_smarty->assign($key,$val);
}

public function __isset($key)
{
$var = $this->_smarty->get_template_vars($key);
if($var)
return true;

return false;
}

public function __unset($key)
{
parent::__unset($key);
$this->_smarty->clear_assign($key);
}

public function assign($spec,$value = null)
{
if($value === null)
$this->_smarty->assign($spec);
else
$this->_smarty->assign($spec,$value);
}


public function clearVars()
{
$this->_smarty->clear_all_assign();
}

protected function _run()
{
$this->strictVars(true);

//why 'this'?
//to emulate standard zend view functionality
//doesn't mess up smarty in any way
$this->_smarty->assign_by_ref('this',$this);

$fileFullname = func_get_arg(0);
$templateDirs = $this->getScriptPaths();

//TODO: find more effective way to get correct template dir
$templateDir = $templateDirs[0];
$file = $fileFullname;
foreach ($templateDirs as $dir) {
if (preg_match("|^$dir|", $fileFullname)) {
$templateDir = $dir;
$file = substr($fileFullname,strlen($templateDir));
break;
}
}
//$file = substr(func_get_arg(0),strlen($templateDir));
//var_dump($templateDir, $file);
$this->_smarty->template_dir = $templateDir;
$this->_smarty->compile_id = $templateDir;

echo $this->_smarty->fetch($file);
}
}


初始化脚本中设置 view

//Create the view and set the compile dir to template_c
$view = new SmartyView(array(
'compileDir' => './template_c'
));

//Create a new ViewRenderer helper and assign our newly
//created SmartyView object as the view instance
$viewHelper = new Zend_Controller_Action_Helper_ViewRenderer($view);
$viewHelper->setViewSuffix('tpl');

//Save the helper to the HelperBroker
Zend_Controller_Action_HelperBroker::addHelper($viewHelper);

2007年4月10日星期二

使用模块设计 Zend Framework 控制器

启动文件:基本上一样,唯一的区别:
//$frontController->setControllerDirectory('./application/controllers');
//将原来的设置控制器目录改成以下方式:
$frontController->setControllerDirectory(array(
'default' => './application/controllers/',
'admin' => './application/controllers/admin/')
);


index.php
<?php
/**
* Bootstrap file
*/
error_reporting(E_ALL|E_STRICT);
date_default_timezone_set('Asia/Shanghai');

set_include_path('.' . PATH_SEPARATOR . '../library/'
. PATH_SEPARATOR . './application/models'
. get_include_path());

require_once "Zend/Loader.php";
// autoload class
spl_autoload_register(array('Zend_Loader', 'autoload'));

// load configuration
$config = new Zend_Config_Ini('./application/config.ini', 'general');
Zend_Registry::set('config', $config);

// setup database
$db = Zend_Db::factory($config->db->adapter, $config->db->config->asArray());

Zend_Db_Table::setDefaultAdapter($db);

// register the view we are going to use
$view = new Zend_View();
$view->setScriptPath('./application/views');
Zend_Registry::set('view', $view);

$auth = Zend_Auth::getInstance();

// setup controller
$baseUrl = substr($_SERVER['PHP_SELF'], 0,
strpos($_SERVER['PHP_SELF'], '/index.php'));
$frontController = Zend_Controller_Front::getInstance();
$frontController->setBaseUrl($baseUrl);
$frontController->throwExceptions(true);

$frontController->setControllerDirectory(array(
'default' => './application/controllers/',
'admin' => './application/controllers/admin/')
);

// run!
$frontController->dispatch();
?>


default模块:
在application/controllers目录下的IndexController.php原来一样设计,不需要改动:
<?php
class IndexController extends Zend_Controller_Action
{
public function init()
{
}

public function indexAction()
{
}

public function otherAction()
{
}
}
?>


admin模块:
在application/controllers/admin目录下的IndexController.php是这样的。注意类名:admin_IndexController, 这符合目录-类名转换的约定。
<?php
class admin_IndexController extends Zend_Controller_Action
{
public function init()
{
}

public function indexAction()
{
}

public function otherAction()
{
}
}
?>


好了,大功告成,就这么多。
访问的时候和原来是一样的。
http://localhost/ 访问默认模块index控制器indexAction() application/controllers/IndexController.php
http://localhost/admin 访问admin模块index控制器indexAction() application/controllers/admin/IndexController.php