gpt4 book ai didi

php - 将 D3.js 与 symfony2 一起使用

转载 作者:行者123 更新时间:2023-11-30 22:34:33 25 4
gpt4 key购买 nike

我刚开始学习 php 几个星期,现在我正在使用 Symfony2 作为框架。所以,我对使用 Symfony 的知识很少。

我现在要做的是,我想实现这个 D3 tutorial但我不想使用纯 PHP,而是想使用 Symfony。

那么,我到现在为止做了什么:

  1. 创建了一个名为“homedb”的数据库,我完全按照教程的方式填充它。
  2. 设法将 symfony 连接到数据库(在 parameters.yml 中修改)
  3. 创建了一个名为 TreeBundle 的新包。
  4. 创建了一个名为 DataController 的 Controller 来从数据库中获取数据。
  5. 创建了一个 html.twig 文件来显示数据。

我转换了这个文件:data.php

<?php
$username = "homedbuser";
$password = "homedbuser";
$host = "localhost";
$database="homedb";

$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);

$myquery = "SELECT `date`, `close` FROM `data2`";

$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}

$data = array();

for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}

echo json_encode($data);

mysql_close($server);

进入此文件:DataController.php

<?php
// src/Dependency/TreeBundle/Controller/DataController.php
namespace TreeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;

class DataController extends Controller
{
/**
* @Route("/tree")
*/

public function queryAction()
{
$em = $this->getDoctrine()->getEntityManager();

$query=$em->createQuery(
'SELECT date AND close
FROM data2'
);

$list = $query->getResult();
return new JsonResponse($list);

}
return $list->render('DependencyTreeBundle:Data:simple-graph.html.twig');
}

但是,我得到了这个错误:

Parse Error: syntax error, unexpected 'return' (T_RETURN), expecting function (T_FUNCTION)

我知道这只是我的错误代码中的一个小错误。谁能帮我正确转换这个脚本?

P/S:对于我的 simple-graph.html.twig,我只是使用 {{source(simple-graph.html)}} 来返回内容而不渲染它。

更新 1

我只是按如下方式编辑我的代码以从数据库中获取数据并将其转换为 json。

public function queryAction()
{
$em = $this->getDoctrine()->getManager();

$sql = "
SELECT date,
close
FROM data2
";

$stmt = $this->getDoctrine()->getManager()->getConnection()->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
$json = json_encode($stmt);
return $json-->render('DependencyTreeBundle:query:simple-graph.html.twig');
}

但是,这次我遇到了这个错误: Controller 必须返回一个响应 (Array(0 => Array(date => 1-May-12, close => 58.13) , 1 => 数组(日期 => 2012 年 4 月 30 日,收盘价 => 53.98),......

似乎数据已获取但未能将其转换为 json..

更新 2

这是我的新代码,感谢@adiii4 的建议。但是此代码有错误:尝试从命名空间“Dependency\TreeBundle”加载类“TreeBundle”。您是否忘记了另一个命名空间的“use”语句?

<?php
// src/Dependency/TreeBundle/Controller/DataController.php
namespace Dependency\TreeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;

class DataController extends Controller
{
/**
* @Route("/tree")
*/

public function queryAction()
{
$em = $this->getDoctrine()->getManager();

$sql = "
SELECT date,
close
FROM data2
";

$stmt = $this->getDoctrine()->getManager()->getConnection()- >prepare($sql);

$stmt->execute();

$stmt->fetchAll();

$list = json_encode($stmt);

return $this->render('DependencyTreeBundle:Data:simple-graph.html.twig', array('data' => $list));
}

}

更新 3

我想我设法获取数据并正确转换为 json。现在,我需要通过在 html 文件中调用 D3 来可视化数据。是否可以只将 html 文件嵌入到 Twig 中,然后让 Twig 独自完成剩下的工作?还是我需要将其全部转换为 Twig 语法?

这里是 simple-graph.html 的源代码:

        <!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */

body { font: 12px Arial;}

path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}

.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}

</style>
<body>

<!-- load the d3.js library -->
<script src="http://d3js.org/d3.v3.min.js"></script>

<script>

// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;

// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;

// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);

var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);

// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });

// Adds the svg canvas
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");

// Get the data
d3.json("data.php", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});

// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);

// Add the valueline path.
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));

// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);

});

</script>
</body>

我刚才所做的是,在我的 simple-graph.html.twig 中,我只是将 json 数据外包,然后调用 html 文件来完成其余的工作。显然,我遇到了这个错误:Unable to find template "{}"in DependencyTreeBundle:Data:simple-graph.html.twig at line 2

这是我的 simple-graph.html.twig 中的代码:

{# src/Dependency/TreeBundle/Resources/views/simple-graph.html.twig #}
{{ source(data) }}
{{ source('public/html/simple-graph.html') }}

有人知道吗?我很感激。

最佳答案

你得到第二个错误是因为你不能在一个函数中调用两个 return 语句!由于 symfony 中的 Controller 函数总是期望响应对象,因此您会收到此错误,因为第一个 return 语句返回的不是响应对象:

return $stmt->fetchAll();

您的 Controller 函数需要如下所示:

public function queryAction()
{
$em = $this->getDoctrine()->getManager();
$query=$em->createQuery(
'SELECT date AND close
FROM data2'
);

$list = json_encode($query->getResult());

return $this->render('DependencyTreeBundle:query:simple-graph.html.twig', array('data' => $list));
}

然后你可以像这样在你的模板中输出你的json

{{ source(data) }}

您是否还为您的数据库表创建了一个实体类?

更新

一点改进:

当你使用没有实体的原始 sql 查询时,像这样获取你的数据:

    $conn = $this->get('database_connection');
$list = $conn->fetchAll('SELECT date,close FROM data2');

引用:http://symfony.com/doc/current/cookbook/doctrine/dbal.html

关于php - 将 D3.js 与 symfony2 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32963897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com