2011年6月26日 星期日

$_SERVER的用法

網路上抓下來的
$_SERVER['PHP_SELF'] #當前正在執行腳本的文件名,與 document root相關。
$_SERVER['argv'] #傳遞給該腳本的參數。
$_SERVER['argc'] #包含傳遞給程序的命令行參數的個數(如果運行在命令行模式)。
$_SERVER['GATEWAY_INTERFACE'] #服務器使用的 CGI 規範的版本。例如,「CGI/1.1」。
$_SERVER['SERVER_NAME'] #當前運行腳本所在服務器主機的名稱。
$_SERVER['SERVER_SOFTWARE'] #服務器標識的字串,在響應請求時的頭部中給出。
$_SERVER['SERVER_PROTOCOL'] #請求頁面時通信協議的名稱和版本。例如,「HTTP/1.0」。
$_SERVER['REQUEST_METHOD'] #訪問頁面時的請求方法。例如:「GET」、「HEAD」,「POST」,「PUT」。
$_SERVER['QUERY_STRING'] #查詢(query)的字符串。
$_SERVER['DOCUMENT_ROOT'] #當前運行腳本所在的文檔根目錄。在服務器配置文件中定義。
$_SERVER['HTTP_ACCEPT'] #當前請求的 Accept: 頭部的內容。
$_SERVER['HTTP_ACCEPT_CHARSET'] #當前請求的 Accept-Charset: 頭部的內容。例如:「iso-8859-1,*,utf-8」。
$_SERVER['HTTP_ACCEPT_ENCODING'] #當前請求的 Accept-Encoding: 頭部的內容。例如:「gzip」。
$_SERVER['HTTP_ACCEPT_LANGUAGE']#當前請求的 Accept-Language: 頭部的內容。例如:「en」。
$_SERVER['HTTP_CONNECTION'] #當前請求的 Connection: 頭部的內容。例如:「Keep-Alive」。
$_SERVER['HTTP_HOST'] #當前請求的 Host: 頭部的內容。
$_SERVER['HTTP_REFERER'] #鏈接到當前頁面的前一頁面的 URL 地址。
$_SERVER['HTTP_USER_AGENT'] #當前請求的 User_Agent: 頭部的內容。
$_SERVER['REMOTE_ADDR'] #正在瀏覽當前頁面用戶的 IP 地址。
$_SERVER['REMOTE_HOST'] #正在瀏覽當前頁面用戶的主機名。
$_SERVER['REMOTE_PORT'] #用戶連接到服務器時所使用的端口。
$_SERVER['SCRIPT_FILENAME'] #當前執行腳本的絕對路徑名。
$_SERVER['SERVER_ADMIN'] #管理員信息
$_SERVER['SERVER_PORT'] #服務器所使用的端口
$_SERVER['SERVER_SIGNATURE'] #包含服務器版本和虛擬主機名的字符串。
$_SERVER['PATH_TRANSLATED'] #當前腳本所在文件系統(不是文檔根目錄)的基本路徑。
$_SERVER['SCRIPT_NAME'] #包含當前腳本的路徑。這在頁面需要指向自己時非常有用。
$_SERVER['REQUEST_URI'] #訪問此頁面所需的 URI。例如,「/index.html」。
$_SERVER['PHP_AUTH_USER'] #當 PHP 運行在 Apache 模塊方式下,並且正在使用 HTTP 認證功能,這個變量便是用戶輸入的用戶名。
$_SERVER['PHP_AUTH_PW'] #當 PHP 運行在 Apache 模塊方式下,並且正在使用 HTTP 認證功能,這個變量便是用戶輸入的密碼。
$_SERVER['AUTH_TYPE'] #當 PHP 運行在 Apache 模塊方式下,並且正在使用 HTTP 認證功能,這個變量便是認證的類型。
來源:http://blog.chinaunix.net/u/21041/showart_338744.html


自我測試結果
參考網站  city.winjet.com.tw  伺服器位址
絕對路徑目錄 /var/www/html/
檔案所在位址 /var/www/html/demo/testServer.php
結果
$_SERVER["PHP_SELF"] = /demo/testServer.php
$_SERVER["GATEWAY_INTERFACE"] = CGI/1.1
$_SERVER["SERVER_NAME"] = city.winjet.com.tw
$_SERVER["SERVER_SOFTWARE"] = Apache/2.2.3 (CentOS)
$_SERVER["SERVER_PROTOCOL"] = HTTP/1.1
$_SERVER["REQUEST_METHOD"] = GET
$_SERVER["DOCUMENT_ROOT"] = /var/www/html
$_SERVER["HTTP_ACCEPT"] = */*
$_SERVER["HTTP_CONNECTION"] =
$_SERVER["HTTP_REFERER"] =
$_SERVER["HTTP_USER_AGENT"] = Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C)
$_SERVER["REMOTE_HOST"] =
$_SERVER["REMOTE_PORT"] = 48556
$_SERVER["SCRIPT_FILENAME"] = /var/www/html/demo/testServer.php
$_SERVER["SERVER_ADMIN"] = root@localhost
$_SERVER["PATH_TRANSLATED"] =
$_SERVER["SCRIPT_NAME"] = /demo/testServer.php
$_SERVER["REQUEST_URI"] = /demo/testServer.php
$_SERVER["PHP_AUTH_USER"] =

2011年6月16日 星期四

PHPExcel寫入EXCEL出現memory不足解法

    PHPExcel   版本   1.7.2  記憶體

memory_get_usage(true)  取得記憶體現在使用狀況

strlen(serialize($OBJNAME))   取的指定檔案的長度 (通常用來間接表達大小)

在PHPExcel最被詬病的為當匯出檔案過大時,會因為PHPExcel使用一堆迴圈
而占用許多記憶體,造成記憶體不足。
以自己使用經驗來說,100rows 配上 52cols 就會吃掉4mb多的記憶體
所以一次大概跑2000rows 就會吃掉快100mb,
以PHP預設值最大128MB來說  很快就會被吃光。

目前在1.7.6 自己的解決方法是 
先將檔案存至EXCEL

 // Export to Excel2007 (.xlsx) 匯出成2007
   $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
   $objWriter->save('test.xlsx');

 // Export to Excel5 (.xls) 匯出成2003
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('test.xls');


//再清空吃掉的記憶體
$objPHPExcel->disconnectWorksheets();   //此函數可參考底下
//($objPHPExcel 為一開始new PHPExcel() 的object   )

//就可以一直RUN了~


//附上PHPExcel.php    的   __construct()  與  disconnectWorksheets()

public function __construct()
    {
        // Initialise worksheet collection and add one worksheet
        $this->_workSheetCollection = array();
        $this->_workSheetCollection[] = new PHPExcel_Worksheet($this);
        $this->_activeSheetIndex = 0;

        // Create document properties
        $this->_properties = new PHPExcel_DocumentProperties();

        // Create document security
        $this->_security = new PHPExcel_DocumentSecurity();

        // Set named ranges
        $this->_namedRanges = array();

        // Create the cellXf supervisor
        $this->_cellXfSupervisor = new PHPExcel_Style(true);
        $this->_cellXfSupervisor->bindParent($this);

        // Create the default style
        $this->addCellXf(new PHPExcel_Style);
        $this->addCellStyleXf(new PHPExcel_Style);
    }


    public function disconnectWorksheets() {
        foreach($this->_workSheetCollection as $k => &$worksheet) {
            $worksheet->disconnectCells();
            $this->_workSheetCollection[$k] = null;
        }
        unset($worksheet);
        $this->_workSheetCollection = array();
    }

2011年6月13日 星期一

轉錄---PHPExcel解决内存占用过大问题-设置单元格对象缓存

PHPExcel是一个很强大的处理Excel的PHP开源类,但是很大的一个问题就是它占用内存太大,从1.7.3开始,它支持设置cell的缓存方式,但是推荐使用目前稳定的版本1.7.6,因为之前的版本都会不同程度的存在bug,以下是其官方文档:

PHPExcel1.7.6官方文档 写道

PHPExcel uses an average of about 1k/cell in your worksheets, so large workbooks can quickly use up available memory. Cell caching provides a mechanism that allows PHPExcel to maintain the cell objects in a smaller size of memory, on disk, or in APC, memcache or Wincache, rather than in PHP memory. This allows you to reduce the memory usage for large workbooks, although at a cost of speed to access cell data.

 
PHPExcel平均下来使用1k/单元格的内存,因此大的文档会导致内存消耗的也很快。单元格缓存机制能够允许PHPExcel将内存中的小的单元格对象缓存在磁盘或者APC,memcache或者Wincache中,尽管会在读取数据上消耗一些时间,但是能够帮助你降低内存的消耗。

PHPExcel1.76.官方文档 写道
By default, PHPExcel still holds all cell objects in memory, but you can specify alternatives. To enable cell caching, you must call the PHPExcel_Settings::setCacheStorageMethod() method, passing in the caching method that you wish to use.
 
默认情况下,PHPExcel依然将单元格对象保存在内存中,但是你可以自定义。你可以使用PHPExcel_Settings::setCacheStorageMethod()方法,将缓存方式作为参数传递给这个方法来设置缓存的方式。


Php代码
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory;
PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
  
复制代码
PHPExcel1.7.6官方文档 写道
setCacheStorageMethod() will return a boolean true on success, false on failure (for example if trying to cache to APC when APC is not enabled).
setCacheStorageMethod()方法会返回一个BOOL型变量用于表示是否成功设置(比如,如果APC不能使用的时候,你设置使用APC缓存,将会返回false)

PHPExcel1.7.6官方文档 写道
A separate cache is maintained for each individual worksheet, and is automatically created when the worksheet is instantiated based on the caching method and settings that you have configured. You cannot change the configuration settings once you have started to read a workbook, or have created your first worksheet.

每一个worksheet都会有一个独立的缓存,当一个worksheet实例化时,就会根据设置或配置的缓存方式来自动创建。一旦你开始读取一个文件或者你已经创建了第一个worksheet,就不能在改变缓存的方式了。

PHPExcel1.7.6官方文档 写道
Currently, the following caching methods are available.
目前,有以下几种缓存方式可以使用:

Php代码
PHPExcel_CachedObjectStorageFactory::cache_in_memory;
复制代码
PHPExcel1.7.6官方文档 写道
The default. If you don’t initialise any caching method, then this is the method that PHPExcel will use. Cell objects are maintained in PHP memory as at present.
默认情况下,如果你不初始化任何缓存方式,PHPExcel将使用内存缓存的方式。

===============================================



Php代码
PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;
复制代码
PHPExcle1.7.6官方文档 写道
Using this caching method, cells are held in PHP memory as an array of serialized objects, which reduces the memory footprint with minimal performance overhead.
使用这种缓存方式,单元格会以序列化的方式保存在内存中,这是降低内存使用率性能比较高的一种方案。

===============================================



Php代码
PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
复制代码
PHPExcel1.7.6官方文档 写道
Like cache_in_memory_serialized, this method holds cells in PHP memory as an array of serialized objects, but gzipped to reduce the memory usage still further, although access to read or write a cell is slightly slower.
与序列化的方式类似,这种方法在序列化之后,又进行gzip压缩之后再放入内存中,这回跟进一步降低内存的使用,但是读取和写入时会有一些慢。

===========================================================



Php代码
PHPExcel_CachedObjectStorageFactory::cache_to_discISAM;
复制代码
PHPExcel1.7.6官方文档 写道
When using cache_to_discISAM all cells are held in a temporary disk file, with only an index to their location in that file maintained in PHP memory. This is slower than any of the cache_in_memory methods, but significantly reduces the memory footprint.
The temporary disk file is automatically deleted when your script terminates.

当使用cache_to_discISAM这种方式时,所有的单元格将会保存在一个临时的磁盘文件中,只把他们的在文件中的位置保存在PHP的内存中,这会比任何一种缓存在内存中的方式都慢,但是能显著的降低内存的使用。临时磁盘文件在脚本运行结束是会自动删除。

===========================================================



Php代码
PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
复制代码
PHPExcel1.7.6官方文档 写道
Like cache_to_discISAM, when using cache_to_phpTemp all cells are held in the php://temp I/O stream, with only an index to their location maintained in PHP memory. In PHP, the php://memory wrapper stores data in the memory: php://temp behaves similarly, but uses a temporary file for storing the data when a certain memory limit is reached. The default is 1 MB, but you can change this when initialising cache_to_phpTemp.
类似cache_to_discISAM这种方式,使用 cache_to_phpTemp时,所有的单元格会还存在php://temp I/O流中,只把他们的位置保存在PHP的内存中。PHP的php://memory包裹器将数据保存在内存中,php://temp的行为类似,但是当 存储的数据大小超过内存限制时,会将数据保存在临时文件中,默认的大小是1MB,但是你可以在初始化时修改它:

Php代码
$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
$cacheSettings = array( ' memoryCacheSize '  => '8MB'
                      );
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
复制代码
PHPExcel1.7.6官方文档 写道
The php://temp file is automatically deleted when your script terminates.
php://temp文件在脚本结束是会自动删除。



===========================================================



Php代码
PHPExcel_CachedObjectStorageFactory::cache_to_apc;
复制代码
PHPExcle1.7.6官方文档 写道
When using cache_to_apc, cell objects are maintained in APC with only an index maintained in PHP memory to identify that the cell exists. By default, an APC cache timeout of 600 seconds is used, which should be enough for most applications: although it is possible to change this when initialising cache_to_APC.
当使用cach_to_apc时,单元格保存在APC中,只在内存中保存索引。APC缓存默认超时时间时600秒,对绝大多数应用是足够了,当然你也可以在初始化时进行修改:

Php代码
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_APC;
$cacheSettings = array( 'cacheTime'        => 600
                      );
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
复制代码
PHPExcel1.7.6官方文档 写道
When your script terminates all entries will be cleared from APC, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism.
当脚本运行结束时,所有的数据都会从APC中清楚(忽略缓存时间),不能使用此机制作为持久缓存。



===========================================================

Php代码
PHPExcel_CachedObjectStorageFactory::cache_to_memcache
复制代码
PHPExcel1.7.6官方文档 写道
When using cache_to_memcache, cell objects are maintained in memcache with only an index maintained in PHP memory to identify that the cell exists.
By default, PHPExcel looks for a memcache server on localhost at port 11211. It also sets a memcache timeout limit of 600 seconds. If you are running memcache on a different server or port, then you can change these defaults when you initialise cache_to_memcache:

使用cache_to_memory时,单元格对象保存在memcache中,只在内存中保存索引。默认情况下,PHPExcel会在localhost和端口11211寻找memcache服务,超时时间600秒,如果你在其他服务器或其他端口运行memcache服务,可以在初始化时进行修改:

Php代码
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_memcache;
$cacheSettings = array( 'memcacheServer'  => 'localhost',
                        'memcachePort'    => 11211,
                        'cacheTime'       => 600
                      );
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
复制代码
从初始化设置的形式上看,MS还不支持多台memcache服务器轮询的方式,比较遗憾。

PHPExcel1.7.6官方文档 写道
When your script terminates all entries will be cleared from memcache, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism.
当脚本结束时,所有的数据都会从memcache清空(忽略缓存时间),不能使用该机制进行持久存储。


===========================================================

Php代码
PHPExcel_CachedObjectStorageFactory::cache_to_wincache;
复制代码
PHPExcel1.7.6官方文档 写道
When using cache_to_wincache, cell objects are maintained in Wincache with only an index maintained in PHP memory to identify that the cell exists. By default, a Wincache cache timeout of 600 seconds is used, which should be enough for most applications: although it is possible to change this when initialising cache_to_wincache.
使用cache_towincache方式,单元格对象会保存在Wincache中,只在内存中保存索引,默认情况下Wincache过期时间为600秒,对绝大多数应用是足够了,当然也可以在初始化时修改:

Php代码
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_wincache;
$cacheSettings = array( 'cacheTime'        => 600
                      );
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
复制代码
PHPExcel官方文档1.7.6 写道
When your script terminates all entries will be cleared from Wincache, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism.




呃, 终于“又”写完了,之前写的一版,有的文字是直接从word粘过来的,带了一大堆格式,被截断了,悲了个剧的,翻译文档也不是件容易的事 啊……PHPExcel还是比较强大的,最大的问题就是内存占用的问题,我之前用的1.7.2,还没有这种机制,导出2W+数据,占用了400M+内存, 改成1.7.6,使用cach_to_diskISAM方式,内存降低到200M-,效果还是很明显的,不过依然还是够高的,excel文件5.1M,就 使用了200M-和未知大小的磁盘空间,PHPExcel啥时候能出一个轻量级的版本,不需要那么多花哨的功能,只需要导出最普通的数据的版本就好了!

PHPExcel匯入

    <?PHP

    //include 'PHPExcel.php';
    /** PHPExcel_Writer_Excel2007 */
    //include 'PHPExcel/Writer/Excel2007.php';
    /** Error reporting */
    error_reporting(E_ALL);
    /** PHPExcel */
    require_once 'Classes/PHPExcel.php';
    /** PHPExcel_IOFactory */
    require_once 'Classes/PHPExcel/IOFactory.php';

    $objPHPExcel = new PHPExcel();
    $objPHPExcel->setActiveSheetIndex(0);

    //合併儲存格
    //    $objPHPExcel->getActiveSheet()->mergeCells('A1:D2');

    //設定漸層背景顏色雙色(灰/白)
/*    $objPHPExcel->getActiveSheet()->getStyle('A1:D2')->applyFromArray(
            array(
                'font'    => array(
                    'bold'      => true
                ),
                'alignment' => array(
                    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                ),
                'borders' => array(
                    'top'     => array(
                         'style' => PHPExcel_Style_Border::BORDER_THIN
                     )
                ),
                'fill' => array(
                     'type'       => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
                      'rotation'   => 90,
                     'startcolor' => array(
                         'rgb' => 'DCDCDC'
                     ),
                     'endcolor'   => array(
                         'rgb' => 'FFFFFF'
                     )
                 )
            )
    );
*/
    //設定字型大小
//    $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(16);

    //設定A1欄位顯示文字PHPEXCEL TEST
//    $objPHPExcel->getActiveSheet()->setCellValue('A1','PHPEXCEL TEST');

    //設定字體顏色
    //$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_BLUE);

    //設定背景顏色單色
/*  $objPHPExcel->getActiveSheet()->getStyle('A3:D3')->applyFromArray(
        array('fill'     => array(
                                    'type'        => PHPExcel_Style_Fill::FILL_SOLID,
                                    'color'        => array('rgb' => 'D1EEEE')
                                ),
             )
        );
*/
    //設定欄位值
   
  $link = mysql_connect("localhost","root","ann7blaw");
 
  if(!$link){
    echo "連結資料庫失敗";
    exit();
  }
  mysql_select_db("dydemo");   
  $str = 'select * from member limit 10;';
  $result = mysql_query($str,$link);
 
  $j=array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
  $count=1;
  while($rows = mysql_fetch_row($result))
  {   

    print_r($rows);
   
    for($i=0;$i<51;$i++)
    {
        $row = '';
        $k= $i>=26 ? 'A'.$j[$i-26] : $j[$i];

        echo $k.$count." = ".$rows[$i]."<br>";
        if($rows[50]!='')
        {
            $groups = explode(';',$rows[50])
            foreach($groups as $value)
            {
                $str = 'select group_name from member_group where group_code = '.$value;
               
            }
        }   
           
        $objPHPExcel->getActiveSheet()->setCellValue(a1,value);
   
   
   
    }
    $count++;
 }
    // Rename sheet
  //  $objPHPExcel->getActiveSheet()->setTitle('sheet');

    //設定的欄位寬度(自動)
    $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);

    // Set active sheet index to the first sheet, so Excel opens this as the first sheet
    $objPHPExcel->setActiveSheetIndex(0);

    // Export to Excel2007 (.xlsx) 匯出成2007

   // $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
   // $objWriter->save('test.xlsx');

    // Export to Excel5 (.xls) 匯出成2003

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('test1.xls');
   echo 'success';

    ?>

2011年6月11日 星期六

JavaScript大全14章

14.2瀏覽器的Location和History

.分析URL
從URL中把用&符號分隔的name=value取出

var args = getArgs();
var q = ar.q || "";
var n = args.n ? parseInt(arg.n) : 10 ;

function getArgs () {
   var args = new Object();
   var query = location.search.substring(1);
   var pairs = query.split("&");
   for(var i =0;i<=pairs.length;i++)
   {
       var pos = pairs[i].indexof('=');
       if(pos == -1) continue;
       var argname = pairs[i].substring(0,pos);
       var argvalue = pairs[i].substring(pos+1);
       value = decodeURIComponent(value);
       args[argname]=value;

   }
   return args;
}


//有關視窗位置的讀取設定
var windowWidth = window.outerWidth;     瀏覽器的尺寸
var windowHeight = window.outerHeight;

var windowX = window.screenX;     瀏覽器視窗的位置
var windowY = window.screenY;

var viewportWidth = window.innerWidth;   HTML 文件顯示所在的視野視窗
var viewportHeight = window.innerHeight;


scrollBy()  把視窗顯示的文件往上下或者左右移動
scrollTo()  把視窗顯示的文件往絕對座標值移動

focus() 兩種用法
1.將視窗拉到最上層  通常是配合  window.open 跳至舊有視窗時,將視窗至頂
2.focus()在可接受鍵盤輸入焦點的文件(如表單欄位和按鈕), 可使視窗捲動至該元素可視。

scrollIntoView() 類似focus的第2種用法  但不限制於表單欄位與按鈕

最實在的捲動方式
在想捲動的地點,先以<a name = XXX> 標籤定義錨點
再以  window.location.hash = "#XXX" 就可跳至定義點
並且能以back回到前一個位置
但這樣做會改變瀏覽歷程

另一種方式是使用
window.location.replace("#XXX")
則只是單純捲動至定名錨點  而不擾亂瀏覽歷程

2011年6月6日 星期一

symfony表單

symfony表單將基本的用法定義在sfForm裡面
例如
public function executeContact($request)
{
$this->form = new sfForm();
$this->form->setWidgets(array(
'name' => new sfWidgetFormInputText(),
'email' => new sfWidgetFormInputText(array('default' => 'me@example.com')),
'subject' => new sfWidgetFormChoice(array('choices' => array('Subject A', 'Subject B', 'Subject C'))),
'message' => new sfWidgetFormTextarea(),
));
}



除了一次大量設定外 也可以一個一個設定


// Text input
$form->setWidget('full_name', new sfWidgetFormInput(array('default' => 'John Doe')));
<label for="full_name">Full Name</label>
<input type="text" name="full_name" id="full_name" value="John Doe" />
// Textarea
$form->setWidget('address', new sfWidgetFormTextarea(array('default' => 'Enter your address here'), array('cols' => 20, 'rows' => 5)));
<label for="address">Address</label>
<textarea name="address" id="address" cols="20" rows="5">Enter your address here</textarea>
// Password input
// Note that 'password' type widgets don't take a 'default' parameter for security reasons
$form->setWidget('pwd', new sfWidgetFormInputPassword());
<label for="pwd">Pwd</label>
<input type="password" name="pwd" id="pwd" />
// Hidden input
$form->setWidget('id', new sfWidgetFormInputHidden(array('default' => 1234)));
<input type="hidden" name="id" id="id" value="1234" />
// Checkbox
$form->setWidget('single', new sfWidgetFormInputCheckbox(array('value_attribute_value' => 'single', 'default' => true)));
<label for="single">Single</label>
<input type="checkbox" name="single" id="single" value="true" checked="checked" />



叫出form的方法
render()   (for widget)
renderLabel() 
renderHelp
renderError
renderRow()


設定選項按鍵
当用户不得不从某个列表中选取值,无论是选择一个还是多个,一个单独的组件可以满足要求:choice组件(choice widget)。通过两个可选的参数(multiple,expanded),这个组件将以不同的形式显示:
                             multiple=flase(default)     multiple=true
expanded=false(default)          下拉列表(<select>) 可多选下拉列表

expanded=true                    一组单选按钮          一组多选按钮



設定時間選項 

// Date
$years = range(1950, 1990);
$form->setWidget('dob', new sfWidgetFormDate(array(
'label' => 'Date of birth',
'default' => '01/01/1950', // can be a timestamp or a string understandable by strtotime()
'years' => array_combine($years, $years)
)));
// symfony renders the widget in HTML as
<label for="dob">Date of birth</label>
<select id="dob_month" name="dob[month]">
<option value=""/>
<option selected="selected" value="1">01</option>
<option value="2">02</option>
...
<option value="12">12</option>
</select> /
<select id="dob_day" name="dob[day]">
<option value=""/>
<option selected="selected" value="1">01</option>
<option value="2">02</option>
...
<option value="31">31</option>
</select> /
<select id="dob_year" name="dob[year]">
<option value=""/>
<option selected="selected" value="1950">1950</option>
<option value="1951">1951</option>
...
<option value="1990">1990</option>
</select>
// Time
$form->setWidget('start', new sfWidgetFormTime(array('default' => '12:00')));
// symfony renders the widget in HTML as
<label for="start">Start</label>
<select id="start_hour" name="start[hour]">
<option value=""/>
<option value="0">00</option>
...
<option selected="selected" value="12">12</option>
...
<option value="23">23</option>
</select> :
<select id="start_minute" name="start[minute]">
<option value=""/>
<option selected="selected" value="0">00</option>
<option value="1">01</option>
...
<option value="59">59</option>
</select>
// Date and time
$form->setWidget('end', new sfWidgetFormDateTime(array('default' => '01/01/2008 12:00')));
// symfony为月,日,年,时,分来显示五个下拉列表。
 


其中 array_combine($a,$b)代表將$a的鍵與#b的值結合成新array
<?php
$a = array('green','red','yellow');
$b = array('avocado','apple','banana');
$c = array_combine($a, $b);

print_r($c);

/* Outputs:
Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)
*/
?>

当然,你可以定义日期格式,使用欧洲标准代替国际标准
(%day%/%month%/%year% 代替 %month%/%day%/%year%) 

表单数据验证的处理

事实上,除了仅从用户的输入中取得值表单处理还有很多的事情要做。对于大多数的表单提交来说,应用程序控制器需要作以下几件事:
  • 1.检查数据是否符合一组预先定义好的规则(必添的字段,email的格式等)
  • 2.有选择性地转换一些输入数据从而使之更容易理解(消除空格,转换成PHP格式的日期等)
  • 3.如果数据是无效的,重新显示带有错误信息的表单
  • 4.如果数据是正确的,做一些处理并跳转到另一个动作

訂製驗證器
一个表单对象中,所有的字段必须有一个默认的验证器,就是所有的字段都是必要的。如果你需要设置一个字段为可选的,可以给验证器传递一个required选项并设置为false。例如,下面的例子展示了如何使name字段是必要的和email字段为可选的:
$this->form->setValidators(array(
'name' => new sfValidatorString(),
'email' => new sfValidatorEmail(array('required' => false)),
'subject' => new sfValidatorString(),
'message' => new sfValidatorString(array('min_length' => 4))
));

 使用sfValidatorAnd來使用多個驗證器
$this->form->setValidators(array(
'name' => new sfValidatorString(),
'email' => new sfValidatorAnd(array(
new sfValidatorEmail(),
new sfValidatorString(array('min_length' => 4)),
), array('required' => false)),
'subject' => new sfValidatorString(),
'message' => new sfValidatorString(array('min_length' => 4))
));
 


數個字段使用同一個驗證器 
// in modules/foo/actions/actions.class.php
// 定义表单
$this->form = new sfForm();
$this->form->setWidgets(array(
'login' => new sfWidgetFormInputText(),
'password1' => new sfWidgetFormInputText(),
'password2' => new sfWidgetFormInputText()
);
$this->form->setValidators(array(
'login' => new sfValidatorString(), // login is required
'password1' => new sfValidatorString(), // password1 is required
'password2' => new sfValidatorString(), // password2 is required
));
$this->form->setPostValidators(new sfValidatorSchemaCompare('password1', '==', 'password2'));



底下列舉一些常用驗證器
// 字符串验证器
$form->setValidator('message', new sfValidatorString(array(
'min_length' => 4,
'max_length' => 50,
),
array(
'min_length' => 'Please post a longer message',
'max_length' => 'Please be less verbose',
)));
// 数值验证器
$form->setValidator('age', new sfValidatorNumber(array( // 如果你想验证整型值可使用'sfValidatorInteger'来代替。
'min' => 18,
'max' => 99.99,
),
array(
'min' => 'You must be 18 or more to use this service',
'max' => 'Are you kidding me? People over 30 can\'t even use the Internet',
)));
//邮件地址验证器
$form->setValidator('email', new sfValidatorEmail());
// URL 验证器
$form->setValidator('website', new sfValidatorUrl());
//正则表达式验证器
$form->setValidator('IP', new sfValidatorRegex(array(
'pattern' => '^[0-9]{3}\.[0-9]{3}\.[0-9]{2}\.[0-9]{3}$'
)));



 

2011年5月30日 星期一

Symfony form phpant Class 6

例 6-8 – sfActions 常用方法
class mymoduleActions extends sfActions
{
public function executeIndex(sfWebRequest $request)
{
// Retrieving request parameters
$password = $request->getParameter('password');
// Retrieving controller information
$moduleName = $this->getModuleName();
$actionName = $this->getActionName();
  // Retrieving framework core objects
$userSession = $this->getUser();
$response = $this->getResponse();
$controller = $this->getController();
$context = $this->getContext();
// Setting action variables to pass information to the template
$this->setVar('foo', 'bar');
$this->foo = 'bar'; // Shorter version
}
}


sfController: 控制器对象(->getController())
sfRequest: 请求对象 (->getRequest())
sfResponse: 应答对象 (->getResponse())
sfUser: 用户 session 对象 (->getUser())
sfRouting:路由对象(->getRouting())
sfMailer:邮件对象(->getMailer())
sfI18N:国际化对象 (->getI18N())
sfLogger: 日志对象 (->getLogger())
sfDatabaseConnection: 数据库链接对象 (- >getDatabaseConnection())




正常一般action的結尾 應該為
return sfView::SUCCESS; 

如果有錯 應該這樣結尾
return sfView::ERROR;
symfony 就会去寻找 actionNameError.php 模板。
 
如果你想用一个特别的视图,你可以这样结尾:
return 'MyResult'; 

如果根本就没有或不需要视图—例如,批处理文件的执行–应该这样结尾:
return sfView::NONE; 

用 sfView::NONE 越过视图层直接输出回应
public function executeIndex()
{
$this->getResponse()->setContent("<html><body>Hello, World!</body></html>");
return sfView::NONE;
}
// Is equivalent to
public function executeIndex()
{
return $this->renderText("<html><body>Hello, World!</body></html>");
}


例 6-10 – 避开视图层,但应答有 HTTP 头
public function executeRefresh()
{
$output = '<"title","My basic letter"],["name","Mr Brown">';
$this->getResponse()->setHttpHeader("X-JSON", '('.$output.')');
return sfView::HEADER_ONLY;
}

如果动作需要一个特殊的模板,去掉 return 声明, 用 setTemplate()方法。
$this->setTemplate('myCustomTemplate');

public function executeIndex()
{
$this->setTemplate('myCustomTemplate');
}



From action to action 

跳到另一个动作

在一些情况下,一个动作结束时需要执行另一个动作。例如,一个处理表单提交的动作在更新数据库后通常被跳转到另一个动作上。
动作类里提供了两个方法可以执行另一个动作:
  • 如果动作转发给另一个动作:
  • $this->forward('otherModule', 'index');
  • 如果跳转到另一个动作:
  • $this->redirect('otherModule/index'); $this->redirect('http://www.google.com/'); NOTE forward 与 redirect 之后的动作代码不会被执行。这一点上与 return 语句是一样的。它们会抛出一个 sfStopException 异常来停止动作的执行; 这个异常稍后会被 symfony 截获然后忽略
选择转发或跳转有时并不容易。为了做出最好的选择,请记住转发在应用程序内 部进行,所以对于用户来说比较直接易懂。在用户的眼里,浏览器显示的 URL 和用户请求的 URL 是一样的。 相反地,跳转是一条发给用户浏览器的消息,包括一个新的请求并改变了最终的 URL。

如果一个表单通过 method="post"调用动作,你应该使用跳转。最大的优点是, 如果用户刷新页面,表单不会被重新提交;另外,如果用户点击后退键,浏览器会再显示表单,而不是询问用户是否要重新提交表单。

所以 sfActions 类有几个方法叫 forwardIf(), forwardUnless(), forward404If(), forward404Unless(), redirectIf(),redirectUnless()。这 些方法接受一个参数并且对它进行判断,如果判断结果是 true,xxxIf() 方法


表格 6-1 - sfWebRequest 对象里的方法
名称 功能 输出例子
请求信息
isMethod($method) 是POST还是GET方法 true或者false
getMethod() 请求方法名 'POST'
getHttpHeader('Server') HTTP头值 'Apache/2.0.59 (Unix) DAV/2 PHP/5.1.6'
getCookie('foo') 称作foo人cookie的值 'bar'
isXmlHttpRequest()* 是否是Ajax访问 true
isSecure() 是否是SSL访问 true
请求参数
hasParameter('foo') 请求里是否包含foo true或者false
getParameter('foo') Foo参数的值 bar
setParameterHolder()->getAll() 所有参数数组 array
URI相关信息
getUri() 完整的URI 'http://localhost/frontend_dev.php/mymodule/myaction'
getPathInfo() 路径信息 /mymodule/myaction'
getReferer() Referer(来源) http://localhost/frontend_dev.php/
getHost() 主机名 'localhost'
getScriptName() 前端控制器名 'frontend_dev.php'
客户端浏览器信息
getLanguages() 所有可接受的语言数组 Array( [0] => fr [1] => fr_FR [2] => en_US [3] => en )
getCharsets() 所有可接受的字符集数组 Array( [0] => ISO-8859-1 [1] => UTF-8 [2] => * )
getAcceptableContentTypes() 所有可接受的内容类型数组 Array( [0] => text/xml [1] => text/html
*只能用于prototype,Prototype,Mootools,和 jQuery库
** 有时会被代理服务器阻拦



短暂的属性

删除用户会话属性(如果不再需要这个属性了)是一个常见的问题。例如,在用户提交表单后,你想显示一个确认信息。 当处理表单的动作需要转发到另一个动作时,把信息从一个动作传到另一个动作唯一的办法就是把信息存在用户会话的属性里。在显示确认信息之后,你需要删除这 个属性。否则,这个属性就会 被存入会话里,一直到会话到期。
你只需要定义短暂的属性,而不需要去删除。因为短暂的属性在接受到下一个请 求后会自动删除,使用户会话更清洁。在动作里,你可以这样来定义短暂的属性:
$this->getUser()->setFlash('notice', $value);
用户看到这一页后,发出一个新的请求并触发了下一个动作。在这第二个动作里, 你可以这样取得属性的值:
$value = $this->getFlash('attrib');
删除用户会话属性(如果不再需要这个属性了)是一个常见的问题。例如,在用户提交表单后,你想显示一个确认信息。 当处理表单的动作需要转发到另一个动作时,把信息从一个动作传到另一个动作唯一的办法就是把信息存在用户会话的属性里。在显示确认信息之后,你需要删除这 个属性。否则,这个属性就会 被存入会话里,一直到会话到期。
你只需要定义短暂的属性,而不需要去删除。因为短暂的属性在接受到下一个请 求后会自动删除,使用户会话更清洁。在动作里,你可以这样来定义短暂的属性:
$this->getUser()->setFlash('notice', $value);
用户看到这一页后,发出一个新的请求并触发了下一个动作。在这第二个动作里, 你可以这样取得属性的值:
$value = $this->getFlash('attrib');


会话管理


smfony 把ID 存在客户端的 cookies 上。symfony 的会话 cookies 就叫 symfony,
你可以在factories.yml 設定名稱。
例 6-17 - 在 apps/frontend/config/factories.yml 里,改变会话的 Cookie 名称
all:
   storage:
     class: sfSessionStorage
     param:
       session_name: my_cookie_name


访问限制

例 6-20 - 设置访问限制, 在 apps/frontend/modules/mymodule/config/security.yml 里
read:
   is_secure: false # All users can request the read action
update:
   is_secure: true # The update action is only for authenticated users
delete:
   is_secure: true # Only for authenticated users
   credentials: admin # With the admin credential
all:
   is_secure: false # false is the default value anyway



访问授权

如果要调用设有权限的动作,用户必须被认证后并有相应的证书。你可以用sfUser 对象扩展用户的权限。 setAuthenticated()方法可以改变用户的认证状态,isAuthenticated()方法可以检查用户的认证状态。 例 6-22 是一个用户认证的简单例子。
例 6-22 – 设置用户的认证状态
class myAccountActions extends sfActions
{
public function executeLogin($request)
{
if ($request->getParameter('login') === 'foobar')
{
$this->getUser()->setAuthenticated(true);
}
}
public function executeLogout()
{
$this->getUser()->setAuthenticated(false);
}
}



過濾器 filter還沒看