AJAX in Zend Framework

Posted on 17th April 2008 by Nio in AJAX, JavaScript, Zend Framework, 程序人生

Zend Framework 1.5 已经对 AJAX 有了不错的支持,使用上也很简单。主要涉及到的类是 Zend_Controller_Action_Helper_AjaxContext,这个类中的方法 initContext() 中通过判断 XHR 头来确定是否是 AJAX 调用:


<?php
/**
 * Initialize AJAX context switching
 *
 * Checks for XHR requests; if detected, attempts to perform context switch.
 * 
 * @param  string $format 
 * @return void
 */
public function initContext($format null)
{
    $this->_currentContext null;

    if (!$this->getRequest()->isXmlHttpRequest()) {
        return;
    }

    return parent::initContext($format);
}
?>

可以使用 ZF 默认的目录部署来写一个简单示例,目录结构如下:


application/
    controllers/
        IndexController.php
    models/
    views/
        scripts/
            index/
                index.phtml
                demo.ajax.phtml
        helpers/
        filters/
html/
    .htaccess
    index.php
    js/
        jquery.js

JavaScript 库使用 jQuery。需要写代码的文件是 IndexController.php、index.phtml 和 demo.ajax.phtml。IndexController.php 包含了 2 个 actions,一个是 index,一个是 demo。index 中有个按钮用于测试 AJAX 请求,而请求的目标则是 demo action。demo 对应的视图名字后缀使用了 .ajax.phtml,这是默认的设置。Front controller 的调用很简单:


<?php
require_once 'Zend/Controller/Front.php';
Zend_Controller_Front::getInstance()
    ->setParam('useDefaultControllerAlways'true)
    ->setControllerDirectory('../application/controllers')
    ->dispatch();
?>

IndexController.php 在初始化的时候,需要初始化 AjaxContext Helper:


<?php
class IndexController extends Zend_Controller_Action
{
    public function init()
    {
        $ajaxContext $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('demo''html')
                    ->initContext();
    }
    
    public function indexAction()
    {
    }
    
    public function demoAction()
    {
        $this->view->hello 'Hello, world! ('.date('H:i:s').')';
    }
}

addActionContext('demo', 'html') 表明 demoAction 为 AJAX 调用的 action,格式为 html。除了 html 之外,还支持 xml、json 等。AJAX 请求时需要给请求的 url 加上 format=html 的 GET 参数。indexAction 对应的视图 index.phtml 代码如下:


<html>
<head>
<title>AJAX DEMO</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="<?=$this->url()?>js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#ajax_button').click(function(){ //#ajax_button 的 onclick 事件触发
        var url = '<?=$this->url(array('controller'=>'index','action'=>'demo'))?>'; //AJAX 请求的目标 URL
        $.get(url, {'format':'html'}, function(data){ //这里传递了 format=html 的 GET 参数
            $('#hello_message').html(data); //将 AJAX 返回的内容显示在 #hello_message 里边
        });
    });
});
</script>
</head>

<body>
<p><input type="button" id="ajax_button" value="AJAX Call" />
<p id="hello_message"><p>
</body>

</html>

demoAction 对应的视图 demo.ajax.phtml 内容很简单,只是输出 $hello:


<?=$this->hello?>

这就是一个完整的 AJAX 过程。使用 Zend Framework 写出来的代码其实很简单。如果想更加简单一些,可以写个 jQuery AJAX 的 view helper,封装 jQuery 的 JavaScript 代码。

Zend Framework 还提供了 autocomplete(自动完成)AJAX 的 action helper:Zend_Controller_Action_Helper_AutoCompleteScriptaculousZend_Controller_Action_Helper_AutoCompleteDojo,一个是 for Scriptaculous 的,另一个是 for Dojo 的。

DHH 对 PHP 的认同

Posted on 7th April 2008 by Nio in Ruby & RoR, 程序人生

不容易呀,PHP 在某些方面得到了 Ruby 阵营的 DHH 的认同(The immediacy of PHP):

I've been writing a little bit of PHP again today. That platform has really received an unfair reputation. For the small things I've been used it for lately, it's absolutely perfect.

I love the fact that it's all just self-contained. That the language includes so many helpful functions in the box. And that it managed to get distributed with just about every instance of Apache out there.

For the small chores, being quick and effective matters far more than long-term maintenance concerns. Or how pretty the code is. PHP scales down like no other package for the web and it deserves more credit for tackling that scope.

其实语言就是工具,何必非要比个高低呢。PHP 和 Ruby 各有所长,都有适用的地方,只是有些 fans 太过于狂热了,非要分出个高下来,这就如同“萝卜白菜哪个更好吃”的问题一样,呵呵。

Class Query

Posted on 1st April 2008 by Nio in JavaScript, 程序人生

Class Query 是在 jQuery 之上开发的一个以 class 为主的 JavaScript 库。众所周知,jQuery 语法简单,应用方便,但却由于过于简单,没能提供更加强大的功能,比如 class/object 的扩展,这些对于协调开发都是不可或缺的。在这方面 prototypemootools 做的都比较好。Class Query 正是出于此目的出现的。

看看这段代码:


<script src="jquery.js"></script>
<script src="classy.js"></script>
<script>
jQuery.Events.addEventListener(document, "ready", function(){
  jQuery.querySelectorAll("div").forEach(function(elem){
    jQuery.DOM.append(elem, " <b>More...</b>");
  });
 
  jQuery.querySelectorAll("div b").forEach(function(elem){
    jQuery.Events.addEventListener(elem, "click", function(elem, event){
      var next = jQuery.Traversal.nextSibling(elem);
      var animation = jQuery.Effects.buildAnimation( next, {height: "toggle"});
      amimation.start();
    });
  });
});
</script>

class/object 可以扩展:


jQuery.DOM.boldWrapInner = jQuery.DOM.wrapInner.extend({
  attach: function(elem){
    this._super(elem, "<b></b>");
  }
});

Happy April Fools Day 2008 :)

A Practitioner’s Approach to Performance Testing

Posted on 28th March 2008 by Nio in Testing, 程序人生

A Practitioner's Approach to Performance Testing

The application is horribly slow.", "I don't get the response even after I get my coffee.", "This application is useless". Sounds familiar? How many times have we heard these quotes or or felt like that ourselves? The common thread between these statements is that the performance of the application is not good.

Performance - the (in)famous buzzword. What is it? What does it mean? In this article, we'll touch upon what is involved in testing an application for performance.

With every passing day, organizations are becoming more and more conscious about the performance of their Enterprise Solutions. As the IT industry matures and the technology evolves, so does the awareness about expectations from an Enterprise Application.

Focusing just on the design / implementation and Zero-functional-defect solutions are things of the past. With increasing maturity in technology and IT staff, the 'Non-functional' aspects of the system are fast becoming focus-areas.

So what exactly are the non-functional aspects and/or requirements?

Non-functional requirements (NFRs) tell the IT team, about the kinds of usage and load the application will be subjected to, and the expected response time. We'll go into the details of this "response time" shortly.

NFRs define the Service Level Agreements (SLAs) for the system and hence the overall Performance of the Enterprise Application. Besides performance SLAs, NFRs also cover several other aspects, such as security, but for this article we are concerned with performance related objectives only.

Managing and ensuring the NFRs (SLAs) for an Enterprise Application is called Performance Engineering. Performance engineering is a vast discipline in itself which includes Performance Modeling, Performance Prototyping, Performance Testing, different types of analyses, Performance Tuning, etc. This article will not explain Performance Engineering, Queuing Theory and the science behind the various laws. This article just covers the basics about the Performance Engineering and key activities in Performance Testing. [....]

Zend Framework 1.5RC1 Released

Posted on 28th February 2008 by Nio in AJAX, Zend Framework, 程序人生

貌似不错,开始做 AJAX 部分的开发了,正好拿来用用,省了自己写,呵呵。不过我已经封装了一些常用的 AJAX actions 了,基于 jQuery 的,可以让编程者从 JavaScript 解脱出来,专注于 PHP 部分的编码。

An overview of new features included in the 1.5 Preview Release:

  • New Zend_Form component with support for AJAX-enabled form elements
  • New action and view helpers for automating and facilitating AJAX requests and alternate response formats
  • Infocard and OpenID authentication adapters
  • Support for complex Lucene searches, including fuzzy, date-range, and wildcard queries
  • Support for Lucene 2.1 index file format
  • Partial, Placeholder, Action, and Header view helpers for advanced view composition and rendering
  • New Zend_Layout component for automating and facilitating site layouts
  • UTF-8 support for PDF documents
  • New Technorati and SlideShare web services