sportlog / google-charts
Google图表的PHP包装器
v1.0.3
2023-03-19 16:45 UTC
Requires
- php: >=8.1
Requires (Dev)
- phpstan/phpstan: ^1.6
- phpunit/phpunit: ^9.5
README
PHP包装器,用于Google图表库(《https://developers.google.com/chart/》)
特性
- 类型化的图表选项。您可以使用Intellisense设置任何图表选项。
- 支持的图表:注释、区域、条形图、气泡图、日历、蜡烛图、柱状图、组合、甘特图、仪表、地理图、直方图、折线图、地图、组织图、饼图、散点图、阶梯区域图、表格、时间轴、树状图和词树。
- 可以在经典或Material设计中绘制图表。Material设计仅限于条形图、柱状图、折线图和散点图(仍在Google的Beta测试中)。
使用composer安装
您可以使用composer安装sportlog/google-charts
$ composer require sportlog/google-charts
所需的最小PHP版本是8.1。
如何使用
1. 创建图表服务
创建图表服务实例。您可以可选地提供两个参数
- 设置:某些图表需要mapsApiKey才能工作
- ScriptNonceProvider:图表服务需要加载Google Charts API(《https://www.gstatic.com/charts/loader.js》)。如果您使用《https://en.wikipedia.org/wiki/Content_Security_Policy》中的CSP,您可能需要为脚本提供一个nonce。
$chartService = new ChartService();
最好使用DI为服务!
2. 创建数据
创建一个数据表并添加列和行
$data = new DataTable(); $data->addColumn(new Column(ColumnType::String, 'Task')); $data->addColumn(new Column(ColumnType::Number, 'Hours per Day')); // add the rows: you can also use addRows to add an array of rows $data->addRow(['Work', 11]); $data->addRow(['Eat', 2]); $data->addRow(['Commute', 2]); $data->addRow(['Watch TV', 2]); $data->addRow(['Sleep', 7]);
或者,您也可以使用工厂函数,它会自动通过推断第一行数据的类型来创建列。这会导致与上面相同的结果
$data = DataTable::fromArray( [ ['Task', 'Hours per Day'], ['Work', 11], ['Eat', 2], ['Commute', 2], ['Watch TV', 2], ['Sleep', 7] ] );
3. 创建图表
通过在ChartService上使用工厂函数创建图表。
// pass a unique id to the chart; you will need it to draw it $chart = $chartService->createPieChart('dailyActivities', $data); // set options by using intellisense; for documentation see Google-Charts Homepage $chart->options->title = 'My Daily Activities'; $chart->options->pieHole = 0.4; $chart->options->width = 900; $chart->options->height = 500;
4. 绘制图表
使用ChartService渲染您的图表。如果您使用模板引擎(如Latte、Twig、...),您应该添加一个过滤器。
// draw the chart; you can omit the id if you want to draw all charts echo $chartService->render('dailyActivities');
示例
在示例文件夹中,您至少可以找到一个每个图表的示例。