Symfony - 實戰示例



本章將學習如何在Symfony框架中建立一個完整的基於MVC的圖書商店應用程式。以下是步驟。

步驟1:建立專案

讓我們使用以下命令在Symfony中建立一個名為“BookStore”的新專案。

symfony new BookStore

步驟2:建立控制器和路由

在“src/AppBundle/Controller”目錄中建立一個BooksController。其定義如下。

BooksController.php

<?php  
namespace AppBundle\Controller;  

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

class BooksController { 
   /** 
      * @Route("/books/author") 
   */ 
   public function authorAction() { 
      return new Response('Book store application!'); 
   } 
}

現在,我們已經建立了一個BooksController,接下來建立一個檢視來渲染操作。

步驟3:建立檢視

讓我們在“app/Resources/views/”目錄中建立一個名為“Books”的新資料夾。在資料夾內,建立一個名為“author.html.twig”的檔案並新增以下更改。

author.html.twig

<h3> Simple book store application</h3> 

現在,在BooksController類中渲染檢視。其定義如下。

BooksController.php

<?php  
namespace AppBundle\Controller;  

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

class BooksController extends Controller { 
   /** 
      * @Route("/books/author") 
   */ 
   public function authorAction() { 
      return $this->render('books/author.html.twig'); 
   } 
}

目前,我們已經建立了一個基本的BooksController,並且渲染了結果。您可以使用URL“https://:8000/books/author”在瀏覽器中檢視結果。

步驟4:資料庫配置

在“app/config/parameters.yml”檔案中配置資料庫。

開啟檔案並新增以下更改。

parameter.yml

# This file is auto-generated during the composer install  
parameters: 
   database_driver: pdo_mysql 
   database_host: localhost 
   database_port: 3306 
   database_name: booksdb 
   database_user: <database_username> 
   database_password: <database_password> 
   mailer_transport: smtp 
   mailer_host: 127.0.0.1 
   mailer_user: null 
   mailer_password: null 
   secret: 0ad4b6d0676f446900a4cb11d96cf0502029620d 
   
   doctrine: 
      dbal: 
      driver:   pdo_mysql 
      host:     '%database_host%' 
      dbname:   '%database_name%' 
      user:     '%database_user%' 
      password: '%database_password%' 
      charset: utf8mb4 

現在,Doctrine可以連線到您的資料庫“booksdb”。

步驟5:建立資料庫

執行以下命令以生成“booksdb”資料庫。此步驟用於在Doctrine中繫結資料庫。

php bin/console doctrine:database:create

執行命令後,它會自動生成一個空的“booksdb”資料庫。您可以在螢幕上看到以下響應。

它將產生以下結果:

Created database `booksdb` for connection named default 

步驟6:對映資訊

在位於“src/AppBundle/Entity”的Entity目錄中建立一個Book實體類。

您可以使用註解直接傳遞Book類。其定義如下。

Book.php

在檔案中新增以下程式碼。

<?php 
namespace AppBundle\Entity; 
use Doctrine\ORM\Mapping as ORM;  

/** 
   * @ORM\Entity 
   * @ORM\Table(name = "Books") 
*/  
class Book { 
   /** 
      * @ORM\Column(type = "integer") 
      * @ORM\Id 
      * @ORM\GeneratedValue(strategy = "AUTO") 
   */ 
   private $id;  
   
   /** 
      * @ORM\Column(type = "string", length = 50) 
   */ 
   private $name;  
    
   /** 
      * @ORM\Column(type = "string", length = 50) 
   */ 
      
   private $author;
   /** 
      * @ORM\Column(type = "decimal", scale = 2) 
   */ 
   private $price; 
}  

這裡,表名是可選的。

如果未指定表名,則將根據實體類的名稱自動確定表名。

步驟7:繫結實體

Doctrine 為您建立簡單的實體類。它可以幫助您構建任何實體。

執行以下命令以生成實體。

php bin/console doctrine:generate:entities AppBundle/Entity/Book

然後您將看到以下結果,並且實體將被更新。

Generating entity "AppBundle\Entity\Book” 
   > backing up Book.php to Book.php~ 
   > generating AppBundle\Entity\Book 

Book.php

<?php  
namespace AppBundle\Entity;  

use Doctrine\ORM\Mapping as ORM;  
/** 
   * @ORM\Entity 
   * @ORM\Table(name = "Books") 
*/ 
class Book { 
   /** 
      * @ORM\Column(type = "integer") 
      * @ORM\Id
      * @ORM\GeneratedValue(strategy = "AUTO") 
   */ 
   private $id;  
    
   /** 
      * @ORM\Column(type = "string", length = 50) 
   */ 
   private $name;  
    
   /** 
      * @ORM\Column(type = "string", length = 50) 
   */ 
   private $author;  
    
   /** 
      * @ORM\Column(type = "decimal", scale = 2) 
   */ 
   private $price;  
    
   /** 
      * Get id 
      * 
      * @return integer 
   */ 
   public function getId() { 
      return $this->id; 
   }  
   
   /** 
      * Set name 
      * 
      * @param string $name 
      * 
      * @return Book 
   */
   public function setName($name) { 
      $this->name = $name; 
      return $this; 
   }  
    
   /** 
      * Get name 
      * 
      * @return string 
   */ 
   public function getName() { 
      return $this->name; 
   }  
    
   /** 
      * Set author 
      * 
      * @param string $author 
      * 
      * @return Book 
   */ 
   public function setAuthor($author) { 
      $this->author = $author; 
      return $this; 
   }  
    
   /** 
      * Get author 
      * 
      * @return string 
   */ 
   public function getAuthor() {
      return $this->author; 
   }  
   
   /** 
      * Set price 
      * 
      * @param string $price 
      * 
      * @return Book 
   */ 
   public function setPrice($price) { 
      $this->price = $price; 
      return $this; 
   }  
    
   /** 
      * Get price 
      * 
      * @return string 
   */ 
   public function getPrice() { 
      return $this->price; 
   } 
}     

步驟8:對映驗證

建立實體後,應使用以下命令驗證對映。

php bin/console doctrine:schema:validate 

它將產生以下結果:

[Mapping]  OK - The mapping files are correct
[Database] FAIL - The database schema is not in sync with the current mapping file.

由於我們尚未建立Books表,因此實體不同步。讓我們在下一步中使用Symfony命令建立Books表。

步驟9:建立模式

Doctrine可以自動建立Book實體所需的所有資料庫表。這可以使用以下命令完成。

php bin/console doctrine:schema:update --force

執行命令後,您將看到以下響應。

Updating database schema... 
Database schema updated successfully! "1" query was executed 

現在,再次使用以下命令驗證模式。

php bin/console doctrine:schema:validate 

它將產生以下結果:

[Mapping]  OK - The mapping files are correct. 
[Database] OK - The database schema is in sync with the mapping files. 

步驟10:Getter和Setter

如“繫結實體”部分所示,以下命令將為Book類生成所有getter和setter。

$ php bin/console doctrine:generate:entities AppBundle/Entity/Book

步驟11:從資料庫獲取物件

在BooksController中建立一個方法,該方法將顯示書籍詳細資訊。

BooksController.php

/** 
   * @Route("/books/display", name="app_book_display") 
*/ 
public function displayAction() { 
   $bk = $this->getDoctrine()
   ->getRepository('AppBundle:Book') 
   ->findAll(); 
   return $this->render('books/display.html.twig', array('data' => $bk)); 
}

步驟12:建立檢視

讓我們建立一個指向display操作的檢視。移動到views目錄並建立檔案“display.html.twig”。在檔案中新增以下更改。

display.html.twig

{% extends 'base.html.twig' %} 
{% block stylesheets %} 
   <style> 
      .table { border-collapse: collapse; } 
      .table th, td { 
         border-bottom: 1px solid #ddd; 
         width: 250px; 
         text-align: left; 
         align: left; 
      } 
   </style> 
{% endblock %}  
{% block body %} 
   <h2>Books database application!</h2>  
   <table class = "table">  
      <tr>  
         <th>Name</th>  
         <th>Author</th>  
         <th>Price</th>  
      </tr>  
      {% for x in data %} 
      <tr>  
         <td>{{ x.Name }}</td>   
         <td>{{ x.Author }}</td>
         <td>{{ x.Price }}</td>  
      </tr>  
      {% endfor %} 
   </table> 
{% endblock %}         

您可以透過在瀏覽器中請求URL“https://:8000/books/display”來獲得結果。

結果

Books Database Application

步驟13:新增圖書表單

讓我們建立一個功能來將圖書新增到系統中。建立一個新頁面,在BooksController中新增newAction方法,如下所示。

// use section 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\Form\Extension\Core\Type\TextType; 
use Symfony\Component\Form\Extension\Core\Type\SubmitType;  

// methods section 
/** 
   * @Route("/books/new") 
*/ 

public function newAction(Request $request) { 
   $stud = new StudentForm();
      $form = $this->createFormBuilder($stud) 
         ->add('name', TextType::class) 
         ->add('author', TextType::class) 
         ->add('price', TextType::class) 
         ->add('save', SubmitType::class, array('label' => 'Submit')) 
         ->getForm();  
   return $this->render('books/new.html.twig', array('form' => $form->createView(),)); 
} 

步驟14:為圖書表單建立檢視

讓我們建立一個指向新操作的檢視。移動到views目錄並建立檔案“new.html.twig”。在檔案中新增以下更改。

{% extends 'base.html.twig' %} 
{% block stylesheets %} 
   <style> 
      #simpleform { 
         width:600px; 
         border:2px solid grey; 
         padding:14px; 
      } 
      #simpleform label { 
         font-size:14px; 
         float:left; 
         width:300px; 
         text-align:right; 
         display:block; 
      } 
      #simpleform span { 
         font-size:11px; 
         color:grey;
         width:100px; 
         text-align:right; 
         display:block; 
      }  
      #simpleform input { 
         border:1px solid grey; 
         font-family:verdana; 
         font-size:14px; 
         color:light blue; 
         height:24px; 
         width:250px; 
         margin: 0 0 10px 10px; 
      }  
      #simpleform textarea { 
         border:1px solid grey; 
         font-family:verdana; 
         font-size:14px; 
         color:light blue; 
         height:120px; 
         width:250px; 
         margin: 0 0 20px 10px; 
      }  
      #simpleform select { 
         margin: 0 0 20px 10px; 
      } 
      #simpleform button { 
         clear:both; 
         margin-left:250px; 
         background: grey;
         color:#FFFFFF; 
         border:solid 1px #666666; 
         font-size:16px; 
      } 
   </style> 
{% endblock %}  
{% block body %} 
   <h3>Book details:</h3> 
   <div id = "simpleform"> 
      {{ form_start(form) }} 
      {{ form_widget(form) }} 
      {{ form_end(form) }} 
   </div> 
{% endblock %}    

它將產生以下螢幕作為輸出:

Book Details

步驟15:收集圖書資訊並存儲它

讓我們更改newAction方法幷包含處理表單提交的程式碼。此外,將圖書資訊儲存到資料庫中。

/**
   * @Route("/books/new", name="app_book_new") 
*/ 
public function newAction(Request $request) { 
   $book = new Book(); 
   $form = $this->createFormBuilder($book) 
      ->add('name', TextType::class) 
      ->add('author', TextType::class) 
      ->add('price', TextType::class) 
      ->add('save', SubmitType::class, array('label' => 'Submit')) 
      ->getForm();  
   
   $form->handleRequest($request);  
   
   if ($form->isSubmitted() && $form->isValid()) { 
      $book = $form->getData(); 
      $doct = $this->getDoctrine()->getManager();  
      
      // tells Doctrine you want to save the Product 
      $doct->persist($book);  
      
      //executes the queries (i.e. the INSERT query) 
      $doct->flush();  
      
      return $this->redirectToRoute('app_book_display'); 
   } else { 
      return $this->render('books/new.html.twig', array( 
         'form' => $form->createView(), 
      )); 
   } 
}        

將圖書儲存到資料庫後,重定向到圖書顯示頁面。

步驟16:更新圖書

要更新圖書,請建立一個操作updateAction,並新增以下更改。

/** 
   * @Route("/books/update/{id}", name = "app_book_update" ) 
*/ 
public function updateAction($id, Request $request) { 
   $doct = $this->getDoctrine()->getManager(); 
   $bk = $doct->getRepository('AppBundle:Book')->find($id);  
    
   if (!$bk) { 
      throw $this->createNotFoundException( 
         'No book found for id '.$id 
      ); 
   }  
   $form = $this->createFormBuilder($bk) 
      ->add('name', TextType::class) 
      ->add('author', TextType::class) 
      ->add('price', TextType::class) 
      ->add('save', SubmitType::class, array('label' => 'Submit')) 
      ->getForm();  
   
   $form->handleRequest($request);  
   
   if ($form->isSubmitted() && $form->isValid()) { 
      $book = $form->getData(); 
      $doct = $this->getDoctrine()->getManager();  
      
      // tells Doctrine you want to save the Product 
      $doct->persist($book);  
        
      //executes the queries (i.e. the INSERT query) 
      $doct->flush(); 
      return $this->redirectToRoute('app_book_display'); 
   } else {  
      return $this->render('books/new.html.twig', array(
         'form' => $form->createView(), 
      )); 
   } 
}        

在這裡,我們正在處理兩個功能。如果請求只包含id,則我們從資料庫中獲取它並在圖書表單中顯示它。並且,如果請求包含完整的圖書資訊,則我們更新資料庫中的詳細資訊並重定向到圖書顯示頁面。

步驟17:刪除物件

刪除物件需要呼叫實體(doctrine)管理器中的remove()方法。

這可以使用以下程式碼完成。

/** 
   * @Route("/books/delete/{id}", name="app_book_delete") 
*/ 
public function deleteAction($id) { 
   $doct = $this->getDoctrine()->getManager(); 
   $bk = $doct->getRepository('AppBundle:Book')->find($id); 
   
   if (!$bk) { 
      throw $this->createNotFoundException('No book found for id '.$id); 
   } 
   $doct->remove($bk); 
   $doct->flush(); 
   return $this->redirectToRoute('app_book_display'); 
} 

在這裡,我們刪除了圖書並重定向到圖書顯示頁面。

步驟18:在顯示頁面中包含新增/編輯/刪除功能

現在,更新display檢視中的body塊,幷包含新增/編輯/刪除連結,如下所示。

{% block body %} 
   <h2>Books database application!</h2> 
   <div> 
      <a href = "{{ path('app_book_new') }}">Add</a> 
   </div> 
   <table class = "table">  
      <tr>  
         <th>Name</th>  
         <th>Author</th>  
         <th>Price</th> 
         <th></th> 
         <th></th> 
      </tr>  
      {% for x in data %} 
      <tr>  
         <td>{{ x.Name }}</td>   
         <td>{{ x.Author }}</td>   
         <td>{{ x.Price }}</td>   
         <td><a href = "{{ path('app_book_update', { 'id' : x.Id }) }}">Edit</a></td>
         <td><a href = "{{ path('app_book_delete', { 'id' : x.Id }) }}">Delete</a></td>
      </tr>  
      {% endfor %} 
   </table>  
{% endblock %} 

它將產生以下螢幕作為輸出:

Books Database Application

Symfony 包含一組 PHP 元件、一個應用程式框架、一個社群和一種理念。Symfony 極其靈活,能夠滿足高階使用者、專業人士的所有需求,並且是所有 PHP 初學者的理想選擇。

廣告