# 書籍詳情頁面
第二個我們要詳細解釋的頁面編程是書籍詳情。
在該頁面中我們要顯示很多東西:書籍的所有登陸信息,包括TAG,一個jQuery的表單方便訪客增加自己的TAG,如果這本書有相關的評論,那么還要顯示評論的連接等等等等。該頁面編程量非常大,請做好準備。
## 創建`detail.html.twig`頁面
這個頁面很長,我這里就不貼出全部的代碼了。同時我也不會寫出所有的步驟:一般而言,SF給出的錯誤提示是非常精確的。在過程中參考錯誤提示,不斷地修訂——增加路由,控制器方法,模板等,最終一定能調試通過。
我們貼一張最終渲染的效果圖:

我們分別來看幾個重要的版塊。
## 顯示書籍封面圖片
我們這里要顯示的書籍封面圖片,以JPG圖片格式保存在`web/covers`目錄之下,每本書都對應一個圖片,其格式是`{{bookid}}.jpg`,例如途中所示的書其`bookid`為`99999`,那么它對應的封面圖片應該是`99999.jpg`。如果該文件名的圖片不存在,我們將顯示一個`default.jpg`。
但是我們不是簡單地顯示圖片,而是要加一個水印。同時,對于缺省圖片,我們需要根據必要的書籍信息(書名、作者)在缺省圖片上顯示。因此,雖然只有一個缺省圖片,其最終效果是動態的。
我們先看其路由定義:
~~~
cover:
path: /books/cover/{id}_{title}_{author}_{width}.png
defaults: {_controller: AppBundle:Default:cover, width: 300}
requirements:
title: .+
~~~
從路由定義我們可以看到,我們的圖片是動態生成的。
再看對應的動作,我們將其放置在`DefaultController`中的`cover`動作中:
~~~
public function coverAction($id, $title, $author, $width)
{
// Construct image file name based on
$path = 'covers/';
$ext = '.jpg';
$filename = $path . $id . $ext;
$default = false;
// Check if the file exists
if (!file_exists($filename))
{
$filename = $path . 'default' . $ext;
$default = true;
}
list($w, $h) = getimagesize($filename);
$nw = 300;
$nh = $nw / $w * $h; // Propotionally change the width/height
// Resize image
$oimg = imagecreatefromjpeg($filename);
$nimg = imagecreatetruecolor($nw, $nh);
imagecopyresampled($nimg, $oimg, 0, 0, 0, 0, $nw, $nh, $w, $h);
// Print copyright texts
$copytext1 = "任氏有無軒";
$copytext2 = "版權所有";
$copytext3 = "1989-" . date("Y");
$color = imagecolorallocate($nimg, 255, 255, 255);
$color2 = imagecolorallocate($nimg, 0, 0, 0);
$font = $path . 'msyh.ttf';
imagettftext($nimg, 10, 0, 10, 26, $color, $font, $copytext1);
imagettftext($nimg, 10, 0, 10, 40, $color, $font, $copytext2);
imagettftext($nimg, 10, 0, 10, 54, $color, $font, $copytext3);
if ($default)
{
//Print title
imagettftext($nimg, 12, 0, 10, 140, $color2, $font, $title);
// Print author
imagettftext($nimg, 24, 0, 10, 240, $color, $font, $author);
}
//Resize the image to fit into reading list
if ($width <> 300) //300 is the image width for book detail
{
$height = $width / $nw * $nh;
$timg = imagecreatetruecolor($width, $height);
imagecopyresampled($timg, $nimg, 0, 0, 0, 0, $width, $height, $nw, $nh);
}
// Output the image
header('Content-type: image/png');
if ($width == 300)
{
imagepng($nimg, null, 9);
}
else
{
imagepng($timg, null, 9);
}
imagedestroy($nimg);
imagedestroy($oimg);
imagedestroy($timg);
}
~~~
這段代碼比較長,用到了PHP的GD擴展對圖片進行操作。但是流程還是比較直觀,請讀者自行分析。
注意:圖片處理過程中要用到字體文件。由于字體文件比較大,作者沒有將其放入代碼倉庫中,請讀者自行拷貝。
## 顯示TAG并允許用戶自行添加TAG
顯示TAG的過程比較簡單,直接貼代碼:
~~~
public function tagsbyidAction($id)
{
$tags = json_decode(file_get_contents("http://api/book/tagsByBookId/$id"))->out;
return $this->render("AppBundle:book:tags.html.twig", array('tags' => $tags));
}
~~~
我們用的是嵌入控制器的方式,所以對應的模板中代碼如下:
~~~
<small>{{ render (controller('AppBundle:Book:tagsbyid', {"id":book.id})) }}</small>
~~~
顯示完書籍的TAG后,我們顯示一個按鈕,讓用戶能添加自己的TAG:
~~~
<a class="btn btn-info btn-sm" data-toggle="modal" href="#addtag" >增加更多TAG ?</a><br/>
... ...
<!-- The modal dialog to add more tags -->
<div>
<div class="modal fade" id="addtag">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">增加自己的TAG</h4>
</div>
<div class="modal-body">
<form role="form" method="post" action="{{path('tags_add')}}" id='tagform' name='tagform'>
<div class="row">
<div class="col-sm-4 form-group">
<label class="control-label" for="newtags">新增TAG</label>
<input type="text" class="input-xlarge" id="newtags" name="newtags" />
<p class="help-block">(用空格分隔)</p>
<input type="hidden" value="{{book.id}}" id="id" name="id"/>
</div>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal">取消</a>
<button type="submit" class="btn btn-primary">保存</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Example row of columns -->
</div>
~~~
這是標準jQuery的模態對話框。我們不進行特別的分析。只是提請大家注意表單的編寫方式。
## 獲取豆瓣信息
我們希望從第三方(豆瓣)獲取書籍的一些信息(TAG、介紹、評分等)。這里我們要用到已經用了很多次的`file_get_contents`函數:
~~~
public function detailAction($id, Request $request)
{
$logger = $this->createLogger();
$books = json_decode(file_get_contents("http://api/book/bookByBookId/$id"))->out;
if (count($books) == 0) // Book not found
{
return $this->render("AppBundle:book:BookNotFound.html.twig", array('bookid' => $id));
}
$book = $books[0];
$isbn = $book->isbn;
$douban = json_decode(file_get_contents("http://api/douban/douban/$isbn"))->out;
if ($douban->summary == '(豆瓣找不到)')
{
$logger->addError('豆瓣找不到ISBN ' . $book->isbn . '的書:' . $book->title);
}
else
{
$logger->addInfo('豆瓣找到ISBN ' . $book->isbn . '的書:' . $book->title);
}
$lvt = json_decode(file_get_contents("http://api/book/lastvisit/" . $book->bookid))->out;
$session = $request->getSession();
$count = $session->get('addvc', 1);
$session->remove('addvc');
$vc = json_decode(file_get_contents("http://api/book/visitCount/" . $book->id . "," . $count))->out;
return $this->render("AppBundle:book:detail.html.twig", array('book' => $book, 'douban' => $douban, 'vc' => $vc, 'lvt' => $lvt));
}
~~~
注意到我們此時用的是傳遞變量到模板的方式。但是方法本身全部采用RESTful API調用的方式。
## 獲得相關評論
基于我們的樣本數據,這本書應該有2個評論文章。所以我們還要獲取相應的評論并顯示。該段代碼比較簡單,請讀者自行完成。
## 小結
至此,我們已經基本完成書籍詳情頁面的編寫。
請讀者認真學習本段,因為本段牽涉到的代碼量是非常大的。
- 引言
- 1 LAMP
- 1.1 安裝虛擬機
- 1.2 安裝Vagrant
- 1.3 安裝Ubuntu
- 1.4 安裝Apache 2
- 1.5 安裝PHP
- 1.6 安裝MySQL服務器
- 1.7 最后的微調
- 1.8 設置一個虛擬主機
- 1.9 一個趁手的IDE
- 2 Symfony 3和重要構件
- 2.1 Symfony 3
- 2.2 Doctrine
- 2.3 Twig
- 2.4 Composer
- 3 Symfony重要概念
- 3.1 MVC
- 3.2 Bundle/包
- 3.3 Route/路由
- 3.4 Controller/控制器
- 3.5 Entity/實體
- 3.6 Repository/倉庫
- 3.7 Template/模板
- 3.8 Test/測試
- 4 藏書管理程序的結構
- 5 創建應用
- 5.1 建立版本管理
- 5.2 建立數據庫
- 5.3 應用結構
- 5.4 建立數據庫實體
- 5.5 樣本數據
- 5.6 路由
- 5.7 模板
- 5.8 開始編寫首頁
- 5.9 書籍詳情頁面
- 5.10 書籍列表頁面
- 5.11 書籍搜索
- 6 用戶和后臺
- 7 結語