在 symfony2 中使用 D3.js
Using D3.js with symfony2
我刚开始学习 php 几个星期,现在我正在使用 Symfony2 作为框架。所以,我对使用 Symfony 的知识很少。
我现在想做的是,我想实现这个 D3 tutorial 而不是使用普通的 php,我想使用 Symfony。
所以,我到现在为止做了什么:
- 创建了一个名为 'homedb' 的数据库,我完全按照教程进行填充。
- 设法将 symfony 连接到数据库(在 parameters.yml 中修改)
- 创建了一个新的包调用 TreeBundle。
- 创建了一个名为 DataController 的控制器来从数据库中获取数据。
- 创建了一个 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 :对于我的简单图表。html.twig,我只是使用 {{source(simple-graph.html)}}
只 return 内容而不渲染它。
更新 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 的建议。但是这段代码有错误:Attempted to load class "TreeBundle" from namespace "Dependency\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 语法?
这里是简单的源代码-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>
我刚才所做的,在我的简单图表中。html.twig 是,我只是将 json 数据外包,然后调用 html 文件来完成其余的工作。显然,我遇到了这个错误:无法在 DependencyTreeBundle:Data:simple-graph.html.twig 中的第 2 行
中找到模板“{}”
这是我的简单图表中的代码。html.twig :
{# src/Dependency/TreeBundle/Resources/views/simple-graph.html.twig #}
{{ source(data) }}
{{ source('public/html/simple-graph.html') }}
有人知道吗?我很感激。
您收到第二个错误,因为您不能在一个函数中调用两个 return 语句!由于 symfony 中的控制器函数总是期望响应对象,因此您会收到此错误,因为第一个 return 语句 returns 不是响应对象:
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) }}
您是否还为数据库 table 创建了一个实体 class?
更新
稍作改进:
当您使用没有实体的原始 sql 查询时,会像这样获取您的数据:
$conn = $this->get('database_connection');
$list = $conn->fetchAll('SELECT date,close FROM data2');
参考:http://symfony.com/doc/current/cookbook/doctrine/dbal.html
我刚开始学习 php 几个星期,现在我正在使用 Symfony2 作为框架。所以,我对使用 Symfony 的知识很少。
我现在想做的是,我想实现这个 D3 tutorial 而不是使用普通的 php,我想使用 Symfony。
所以,我到现在为止做了什么:
- 创建了一个名为 'homedb' 的数据库,我完全按照教程进行填充。
- 设法将 symfony 连接到数据库(在 parameters.yml 中修改)
- 创建了一个新的包调用 TreeBundle。
- 创建了一个名为 DataController 的控制器来从数据库中获取数据。
- 创建了一个 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 :对于我的简单图表。html.twig,我只是使用 {{source(simple-graph.html)}}
只 return 内容而不渲染它。
更新 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 的建议。但是这段代码有错误:Attempted to load class "TreeBundle" from namespace "Dependency\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 语法?
这里是简单的源代码-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>
我刚才所做的,在我的简单图表中。html.twig 是,我只是将 json 数据外包,然后调用 html 文件来完成其余的工作。显然,我遇到了这个错误:无法在 DependencyTreeBundle:Data:simple-graph.html.twig 中的第 2 行
中找到模板“{}”这是我的简单图表中的代码。html.twig :
{# src/Dependency/TreeBundle/Resources/views/simple-graph.html.twig #}
{{ source(data) }}
{{ source('public/html/simple-graph.html') }}
有人知道吗?我很感激。
您收到第二个错误,因为您不能在一个函数中调用两个 return 语句!由于 symfony 中的控制器函数总是期望响应对象,因此您会收到此错误,因为第一个 return 语句 returns 不是响应对象:
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) }}
您是否还为数据库 table 创建了一个实体 class?
更新
稍作改进:
当您使用没有实体的原始 sql 查询时,会像这样获取您的数据:
$conn = $this->get('database_connection');
$list = $conn->fetchAll('SELECT date,close FROM data2');
参考:http://symfony.com/doc/current/cookbook/doctrine/dbal.html