php生成extjs类

  • Post author:
  • Post category:php


这段时间研究extjs的使用,用来做些前端显示。要给同事用,所以临时写了一个简单的生成extjs代码的php类。只提供了一些基本的设置。

<?php
/* extjs的PHP类说明
 * 方法调用说明:--开始--
 *{
 * PHP程序页:
 * 		$extjsChart=new extjsChart();//声明类,2011-10-26之前无需传递任何参数进去
 * 		创建图表:$extjsChart->create('传递画图用的数据数组','图表类型:line曲线,pie饼形图【目前只有这两种图表】','页面显示的ID','图表标题','图表宽度:500','图表高度:300','项目类型:chart')
 * 			create类里数据、图表类型为必填项!
 * 		Exp:$this->chart_line=$extjsChart->create($data_line,'line','chart_line',$data['tit'],'1024','450','chart');
 * HTML页面
 * 		在js代码标签里加入该段即可。
 * 		Ext.onReady(function(){
		{%$loadextjsfile%};

		var donut = true;//不明白
			{%$chart_line%};//$chart_line为从php接收返回的extjs图表代码
		});
 *}
 * 方法调用说明:--结束--
 * 
 * 数据结构:--开始--
 * {
 * PHP下的数据结构,在进行方法调用时,线json_encode转换成json数据,便于extjs处理
 *  fields用于生成图例
 * 	fields下的键值表示相对应的线条,在饼形图里表示相对应的块
 * 		fields有多少键值,则图表有多少条线或块
 * data存储数据
 * 	data[]['name']:曲线图中表示X轴的刻度
 * 					饼形图中表示每个块
 *  data[]['cost/线条一、线条二....']:曲线图中使用['线条一、线条二....']表示每条线的在当前X轴上刻度时的数据,与fields的键值对应
 * 									饼形图中使用cost来显示每个块的值
 * $chartdata=array(
		array(
			"fields"=>
				array("线条一","线条二","....")
			),
		array(
			"data"=>
				array("name"=>'1','线条一'=>'646487','线条二'=>'654878'),
				array("name"=>'1','线条一'=>'646487','线条二'=>'654878'),
				array("name"=>'1','线条一'=>'646487','线条二'=>'654878'),
				......
 *		)
 * )
 * }
 * 数据结构:--结束--
 * 
 * 编辑时间:2011-10-26
 * 编辑人:谭宁宁
 */
class extjsChart
{
	public $title='';
	/*public $width='500';
	public $height='350';
	public $div='Ext.getBody()';*/
	public $layout='fit';

	public $items_type='chart';
	
	function __conststruct()
	{
		$this->loadfile=$this->loadfile();
	}
	
	function loadextjsfile()
	{
		$file="Ext.require(['Ext.data.*']);
			Ext.require('Ext.chart.*');
			Ext.require('Ext.layout.container.Fit')";
		return $file;
	}
	
	/*
	 * 创建图表方法
	 * create($data,$stype,$items_type,$title)
	 * $data为基本数据,$stype为图表的类型,分:pie饼形图、line折线图    这两个参数必须规定
	 * $data有固定的数据格式
	 * $items_type对象类型:即使用extjs创建一个什么,默认是chart图表对象
	 * $title:图表名称,可要可不要
	 */
	function create($data,$stype,$div,$title='',$width='500',$height='350',$items_type='chart')
	{
		$this->data=$data;
		$this->stype=$stype;
		$this->div=$div;
		$this->width=$width;
		$this->height=$height;
		$json_data=json_encode($data);
		$this->dataname=$this->getMicrotime();
		
		$chart='';
		$chart.="window.".$this->dataname."=Ext.create('Ext.data.JsonStore',".($json_data).");";
		$chart.="var panel".time()." = Ext.create('widget.panel',{
				width: ".$width.",
				height: ".$height.",
				title: '$title',
				renderTo: '".$div."',
				layout: '".$this->layout."',";
		$chart.=$this->items($items_type);
		$chart.="})";
		return $chart;
	}
	
	/*
	 * 在创建好的对象里新建一个items项目
	 * $items_type同create()方法的$tiems_type
	 * 默认为chart图表项目
	 */
	function items($items_type)
	{
		$items='';
		$items.="items:{
					xtype: '$items_type',
					id: '".($this->div=='Ext.getBody()' ? 'chart_'.time() : $this->div)."',
					animate: true,
					store: ".$this->dataname.",
					shadow: true,
					legend:
					{ position: 'right'},
					insetPadding: 30,";
		$items.=$this->series($this->stype);
		$items.="}";
		return $items;
	}
	
	function axes($data)
	{
		$axes='';
		$axes.="axes:[{
				type: 'Numeric',
				minimum: 0,
				position: 'left',
				fields: [";
		//该行获取坐标轴的字段?
		$t=1;
		foreach($data['fields'] as $k=>$v) 
		{
			if($k=='name')
			{ continue;}
			$name.="'".$k."'";
			$name.=$t<count($data['fields']) ? ',' : '';
			$t++;
		}
		$axes.=$name."],
				grid:{odd:{opacity: 1,fill: '#ddd',stroke: '#bbb','stroke-width': 0.5}}
				},{
				type: 'Category',
				position: 'bottom',
				fields: ['name']
				}],";
		return $axes;
	}
	
	/*
	 * 画出线条 series()
	 * $stype为图表的类型
	 * 	pie:饼形图
	 * 	line:折现/曲线图
	 */
	function series($stype)
	{
		$data=$this->data;
		$series='';
		switch ($stype)
		{
			case 'pie':
				$series=$this->pie();
				break;
			case 'line':
			default :
				$series=$this->line();
				break;
		}
		return $series;
	}
	function tbar()
	{
		$tbar='';
		$tbar.="tbar: [{
            text: 'Reload Data',
            handler: function() {
                store1.loadData(generateData(6, 20));
            }
        }, {
            enableToggle: true,
            pressed: false,
            text: 'Donut',
            toggleHandler: function(btn, pressed) {
                var chart = Ext.getCmp('chartCmp');
                chart.series.first().donut = pressed ? 35 : false;
                chart.refresh();
            }
        }],";
        return $tbar;
	}
	
	/*
	 * 生成饼形图
	 */
	function pie()
	{
		$series_pie='';
		$series_pie.="series:[{
						type: 'pie',
						field: 'cost',
						showInLegend:true,
						tips:{
							trackMouse: true,
							width: 160,
							height: 60,
							renderer: function(storeItem, item)
							{
								var total = 0;
								".$this->dataname.".each(function(rec)
								{ total += rec.get('cost'); });

								this.setTitle(storeItem.get('name') + ': ' + Math.round((total==0 ? 0 : storeItem.get('cost')/total * 100)) + '%');
							}
						},
						highlight:{
							segment: { margin: 20 }
		                },
						label:{	field: 'name', display: 'rotate', contrast: true, font: '18px 幼圆'}
					}]";
		return $series_pie;
	}
	
	/*
	 * 生成折线图
	 */
	function line()
	{
		$data=$this->data;
		unset($data['fields']['name']);
		
		$series_line='';
		$series_line.=$this->axes($data);
		$series_line.='series:[';
		$t=1;
		foreach($data['fields'] as $k=>$v)
		{
			$series_line.="{type: 'line',
						highlight: {size: 10,radius: 1},
						axis: 'left',
						xField: 'name',
						yField: '".$k."',
						tips:{
							trackMouse: true,width: 150,height: 60,
							renderer: function(storeItem, item)
							{ this.setTitle('".$k."'+'-'+storeItem.get('name')+'<br />'+storeItem.get('".$k."'));}
						},
						markerConfig: {type: 'cross',size: 4,radius: 4,'stroke-width': 0}";
			$series_line.=$t<count($data['fields']) ? '},':'}]';
			$t++;
		}
		return $series_line;
	}
	
	/*
	 * 创建一个表格
	 * 需要参数:$data,$div;
	 * 数据格式:
	 * 		array();
	 */
	function create_grid($data,$div='Ext.getBody()',$width='',$height='')
	{
		$grid_name=$this->getMicrotime();
		
		$grid_JS='';
		$grid_JS.="
			Ext.Loader.setConfig({enabled: true});
			Ext.Loader.setPath('Ext.ux', '../ux/');
			Ext.require(['Ext.data.*','Ext.grid.*','Ext.util.*','Ext.ux.data.PagingMemoryProxy','Ext.ux.ProgressBarPager']);";
		
		$grid_data="var ".$grid_name."=Ext.create('Ext.data.ArrayStore',".json_encode($data).");";
		
		$grid_JS.=$grid_data;
		
		$grid_table="Ext.create('Ext.grid.Panel',{";
		$grid_table.=$this->width($width);
		$grid_table.=$this->height($height);
		$grid_table.=$this->rederTo($div);
		$grid_table.="store:".$grid_name.",
		columns:[";
		//给表格建立索引
		$grid_table_t="";
		$t=0;
		$d=',';
		foreach($data['fields'] as $k=>$v)
		{
			if(count($data['fields'])-$t==1)
			{$d='';}
			$grid_table_t.="{text:'".$v."',dataIndex:'".$v."',flex:1}".$d;
			$t++;
			//echo $t.'-'.$v.'-'.$d.'<br />';
		}
		unset($t);unset($d);
		
		$grid_table.=$grid_table_t."]});";
		
		$grid_JS.=$grid_table;

		return $grid_JS;
	}
	
	function width($width)
	{
		return $width=='' ? '' : 'width:'.$width.',';
	}
	
	function height($height)
	{
		return $width=='' ? '' : 'height:'.$height.',';
	}
	
	function rederTo($rederTo)
	{
		return $rederTo=='' ? 'Ext.getBody()' : 'renderTo:'."'".$rederTo."',";
	}
	
	/*
	 * 获取当前系统的微秒,用于返回一个extjs 对象名,extjs图表的数据对象名不能重复
	 */
	function getMicrotime()
	{
		$time=microtime();
		$t=array();
		$t=explode(" ",$time);
		$t=str_replace('.','', $t);
		return 'data_'.$t[0];
	}
}
?>



版权声明:本文为cntnn11原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。