我刚刚开始学习php几周,现在我正在使用Symfony2作为框架。所以,我使用Symfony的知识很少。
我现在要做的是,我想实现这个D3 tutorial,而不是使用普通的php,我想使用Symfony。
所以,到目前为止我做了什么:
我转换了这个文件: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');
}
但是,这次我收到了这个错误:The controller must return a response (Array(0 => Array(date => 1-May-12, close => 58.13), 1 => Array(date => 30-Apr-12, close => 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文件来完成剩下的工作。显然,我遇到了这个错误:无法在DependencyTreeBundle中找到模板“{}”:数据:第2行的simple-graph.html.twig
以下是我的simple-graph.html.twig中的代码:
{# src/Dependency/TreeBundle/Resources/views/simple-graph.html.twig #}
{{ source(data) }}
{{ source('public/html/simple-graph.html') }}
有人有想法吗?我非常感激。
答案 0 :(得分:0)
你得到第二个错误,因为你不能在函数中调用两个return语句!并且由于symfony中的控制器函数总是需要响应对象,因此第一个返回语句返回NOT响应对象:
return $stmt->fetchAll();
您的控制器功能需要如下所示:
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