2015-10-06 50 views
1

我剛開始學習php幾周,現在我使用Symfony2作爲框架。所以,我很少使用Symfony的知識。與symfony2一起使用D3.js

我現在要做的是,我想實現這個D3 tutorial而不是使用普通的PHP,我想使用Symfony。

所以,我做了什麼至今:

  1. 創建了一個名爲「homedb」數據庫,以及我填滿它完全按照教程一樣。
  2. 管理連接symfony與數據庫(在parameters.yml中修改)
  3. 創建一個新的包調用TreeBundle。
  4. 創建一個名爲DataController的控制器以從數據庫獲取數據。
  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'); 
} 

但是,我得到這個錯誤此時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」。 你忘記了另一個命名空間的「使用」語句嗎?

<?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來可視化數據。是否可能只是在Twig中嵌入html文件,並讓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> 

我現在所做的只是,在我的簡單graph.html.twig是,我只是外包JSON數據和呼叫剩下的就是html文件。很顯然,我被拋出這個錯誤:找不到模板「{}」在DependencyTreeBundle:數據:簡單graph.html.twig第2行

這是我在我的簡單graph.html代碼。小枝:

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

有沒有人有想法?我非常感激。

+0

'return()'在函數之外。這是對的嗎?? –

+0

@NiranjanNRaju:感謝您的快速響應。顯然,它是。對不起,我的愚蠢的錯誤。我會糾正我的腳本。但是,我仍然遇到另一個錯誤。 – zulkhairi

+0

d其他錯誤是什麼? –

回答

0

你得到第二個錯誤,因爲你不能在函數中調用兩個返回語句!而且,由於在symfony的控制器功能總是需要一個響應對象,因爲這首return語句返回不響應對象,你得到這個錯誤:

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

+0

感謝您的回覆。我實現了你的代碼,但是我通過使用原始sql查詢做了輕微的修改,因爲我沒有實體類。但是,我正面臨着另一個錯誤,說*嘗試從命名空間「Dependency \ TreeBundle」加載類「TreeBundle」。你忘了另一個命名空間的「use」語句嗎?* 這是我的文件夾樹 -src -Dependency -TreeBundle -Controller + DataController。php – zulkhairi

+0

你能告訴我你的文件的完整代碼嗎? – adiii4

+0

你的Dependency/Treebundle的結構是怎樣的?我相信你的命名空間有問題。 – adiii4