Symfony學習十分鐘入門經典教程,symfony十分鐘_PHP教程

來源:互聯網
上載者:User

Symfony學習十分鐘入門經典教程,symfony十分鐘


Symfony是一個強大的基於PHP的Web開發架構,在這裡我們用十分鐘的時間來做一個簡單的增刪改查的程式, 任何不熟悉Symfony的人都可以通過這個教程完成自己的第一個Symfony程式。

如果需要這個範例程式的全部原始碼,可以訪問 這裡 ,或者通過下面的方式擷取原始碼:

$git clone https://github.com/saharabear/symfony-sample.git

項目初始化

首先,需要你在自己的電腦中安裝PHP環境並安裝git.這方面的內容屬於基礎內容,網路上有大量的教程,在這裡就不多介紹了,不過要提示的一點是:PHP從5.4開始, 已經內建了測試用伺服器,Symfony也擁抱了這個由PHP內建的伺服器,只需要在命令列中使用$php app/console server:run 就可以 啟動基於Symfony架構的PHP程式進行測試,因此不必要使用XAMPP這一類複雜的Integration Environment,直接安裝PHP並保證在命令列下可以執行php命令就可以了。

然後,我們需要建立一個新的目錄,名字叫symfony-sample,Symfony使用一個叫composer的程式管理各種類庫的依賴關係,因此如果你的機器上 安裝了composer,就可以直接跳過這一步,如果沒有安裝,可以用下面的命令安裝最新版本的composer.

$cd symfony-sample$curl -sS https://getcomposer.org/installer | php

如果希望瞭解更多關於composer的資訊,可以參考這個網站。

安裝完成composer後,我們可以開始安裝當前最新版本的Symfony2.6.0
複製代碼 代碼如下:$php composer.phar create-project symfony/framework-standard-edition mysampleproject/ 2.6.0

安裝過程中,需要填寫資料庫等資訊,在這個例子中,我們會使用mysql資料庫,因此你可以一路按斷行符號鍵,先不要關心這一切配置應該如何填寫。反正 Symfony會在安裝成功後,產生一個設定檔,叫app/config/parameters.yml,下面我會提供一個parameters.yml檔案的 內容樣本,只要複製進去就可以了,先不必關注這麼多細節。

剛才建立mysampleproject以後,在symfony-sample目錄下產生了mysampleproject目錄,我習慣於將程式放在項目的根目錄下,因此執行下面的幾個命令, 就可以把項目從symfony-sample/mysampleproject目錄中,移到symfony-sample目錄中

$mv mysampleproject/* ./$rm -rf mysampleproject

理論上來講,我們已經完成了Symfony項目的建立,不過剛才提到的parameters.yml檔案還沒有解釋。這個parameters.yml是Symfony的全域設定檔, 無論是資料庫配置資訊還是其他的各種配置,都可以放在這個檔案中。下面是我們需要使用的測試用的parameters.yml,記得把最後一行的值修改為一個隨機值

# This file is auto-generated during the composer installparameters:  database_driver: pdo_mysql  database_host: localhost  database_port: 3306  database_name: symfony  database_user: root  database_password: root  mailer_transport: smtp  mailer_host: localhost  mailer_user: null  mailer_password: null  locale: en  secret: ChangeThisLineAsYouWish_ioiuqwoieru

直接用這段,替換掉app/config/parameters.yml檔案中的內容,然後編輯app/config/config.yml,找到下面幾行,把最後一行添加進去並儲存。

driver:  "%database_driver%"host:   "%database_host%"port:   "%database_port%"dbname:  "%database_name%"user:   "%database_user%"password: "%database_password%"charset: UTF8path:   "%database_path%"

好了,這樣我們就完成了基本的Symfony程式的配置,你現在有了一個配置好了資料庫,郵件發送器,日誌系統的基本程式原型。下面,我們就開始編寫自己的Symfony程式。

建立Bundle

先說一下什麼是Bundle。Symfony是以DI為核心的,可能你不知道什麼是DI,沒關係,這不重要,你可以把Symfony的DI理解成為一個功能池,把程式中的所有功能都做成Bundle,或者你把Bundle理解成一組php檔案組合而成的程式就可以。 比如使用者註冊,登入功能做成一個Bundle,你也可以把一個論壇的發帖回貼功能做成一個Bundle,自然也可以把文章管理做成一個Bundle,然後用一個Bundle去調用和配置不同的Bundle,那麼你就可以把網站組裝起來了,而你寫的各種Bundle,在其他的應用程式中還可以繼續複用,這樣寫的Bundle越多,可複用性就越強,製作新項目的時候也越有利。

我們現在就來建立自己的Bundle.在命令列中,使用命令:

$php app/console generate:bundleBundle namespace: Symfony/Bundle/SampleBundleBundle name [SymfonySampleBundle]:Target directory [/home/saharabear/workspace/symfony-sample/src]:Configuration format (yml, xml, php, or annotation): ymlDo you want to generate the whole directory structure [no]? yesDo you confirm generation [yes]? yesGenerating the bundle code: OKChecking that the bundle is autoloaded: OKConfirm automatic update of your Kernel [yes]? yesEnabling the bundle inside the Kernel: OKConfirm automatic update of the Routing [yes]? yes

這樣就成功建立了我們的Bundle,名字叫SymfonySampleBundle,我們使用的Bundle namespace是Symfony/Bundle/SampleBundle,這是一種約定,我們還可以建立其他的Bundle,比如Symfony/Bundle/PostBundle, 或者Symfony/Bundle/ArticleBundle,而對應的Bundle name就分別是SymfonyPostBundle或者SymfonyArticleBundle。你也可以自己建立這幾個Bundle,這並不會影響當前我們的教程。

對了,在我們建立的Bundle中,分別會產生下面幾個目錄:

① Entity:這個目錄並不是必須的,很多情況下只有在產生實體的時候才會產生,放置模型,也就是MVC中的M
② Controller:這個目錄會產生DefaultController.php,你可以在這裡建立自己的Controller控制器,也就是MVC中的C
③ Resources:這個目錄下面還有子目錄,其中views放置的是模板,也就是MVC中的V,而public放置的是靜態檔案,比如js, css, images等等
④ Tests:放置單元測試與整合測試的代碼,在這個範例程式中暫時不需要
⑤ DependencyInjection:與DI相關的目錄,暫時也不需要去瞭解
⑥ SymfonySampleBundle.php:當前這個Bundle的定義檔案

更多細節可以去閱讀Symfony 的官方文檔,而當前的重點是把這個Symfony的範例程式運行起來。

設計實體

在MVC的設計理念中,M是最重要的,因為M表達的內容是商務邏輯。我覺得如果這個地方往深入去探討,會一直探討到富血模型或者貧血模型,不過目前在這個教程中根本 不需要考慮這麼多,你只需要知道實體就是MVC中的M,用於表達商務邏輯。比如說,我們要開發一個文章管理的系統,那麼文章本身就代表的商務邏輯。比如,我們的文章要有 標題,內容,作者,那麼這三項就屬於商務邏輯,而標題不能夠為空白,不能超過200長度,內容不可為空,作者卻是可以為空白的,這些也屬於商務邏輯。同時,這個文章需要被 儲存起來,比如儲存到資料庫中,那麼這個M就應該能夠映射到資料庫的表中。我們把這個M,叫實體。

還是少說廢話,直接上代碼。那麼如何建立實體呢?當然不是從頭一點一點地寫,而是直接用下面的命令產生:

$php app/console generate:doctrine:entityWelcome to the Doctrine2 entity generatorThis command helps you generate Doctrine2 entities.First, you need to give the entity name you want to generate.You must use the shortcut notation like AcmeBlogBundle:Post.The Entity shortcut name: SymfonySampleBundle:ArticleDetermine the format to use for the mapping information.Configuration format (yml, xml, php, or annotation) [annotation]:ymlInstead of starting with a blank entity, you can add some fields now.Note that the primary key will be added automatically (named id).Available types: array, simple_array, json_array, object,boolean, integer, smallint, bigint, string, text, datetime, datetimetz,date, time, decimal, float, blob, guid.New field name (press to stop adding fields): titleField type [string]:Field length [255]: 200New field name (press to stop adding fields): contentField type [string]: textNew field name (press to stop adding fields): authorField type [string]:Field length [255]: 20New field name (press to stop adding fields):Do you want to generate an empty repository class [no]? yesSummary before generationYou are going to generate a "SymfonySampleBundle:Article" Doctrine2 entityusing the "yml" format.Do you confirm generation [yes]? yesEntity generationGenerating the entity code: OKYou can now start using the generated code!

經過這些命令,你會發現在Entity中建立了新的檔案Article.php,代碼如下:

namespace Symfony\Bundle\SampleBundle\Entity;use Doctrine\ORM\Mapping as ORM;/** * Article * * @ORM\Table() * @ORM\Entity(repositoryClass="Symfony\Bundle\SampleBundle\Entity\ArticleRepository") */class Article{  /**   * @var integer   *   * @ORM\Column(name="id", type="integer")   * @ORM\Id   * @ORM\GeneratedValue(strategy="AUTO")   */  private $id;  /**   * @var string   *   * @ORM\Column(name="title", type="string", length=200)   */  private $title;  /**   * @var string   *   * @ORM\Column(name="content", type="text")   */  private $content;  /**   * @var string   *   * @ORM\Column(name="author", type="string", length=20)   */  private $author;  /**   * Get id   *   * @return integer   */  public function getId()  {    return $this->id;  }  /**   * Set title   *   * @param string $title   * @return Article   */  public function setTitle($title)  {    $this->title = $title;    return $this;  }  /**   * Get title   *   * @return string   */  public function getTitle()  {    return $this->title;  }  /**   * Set content   *   * @param string $content   * @return Article   */  public function setContent($content)  {    $this->content = $content;    return $this;  }  /**   * Get content   *   * @return string   */  public function getContent()  {    return $this->content;  }  /**   * Set author   *   * @param string $author   * @return Article   */  public function setAuthor($author)  {    $this->author = $author;    return $this;  }  /**   * Get author   *   * @return string   */  public function getAuthor()  {    return $this->author;  }}

你可以一行不改地使用這些代碼。這時候我們再來做幾個神奇的操作:
複製代碼 代碼如下:$php app/console doctrine:schema:update --force

這個操作,已經協助你通過Article.php建立了資料庫和資料表,你不需要自己操作這個過程,下面我們還會對Article.php進行改造,而到時候只需要重新 執行上面的這個操作,Symfony會協助你自動修改資料庫的表結構。

添加約束

上面我們建立了Article.php,既然這個實體代表了具體的商務邏輯,因此我們要考慮幾個現實的問題:

1. 使用者必須填寫標題和內容
2. 使用者填寫的標題不能超過200個字
3. 使用者可以不填寫作者

這些就屬於商務邏輯,而我們可以修改Article.php如下,以增加相應的商務邏輯的約束:

namespace Symfony\Bundle\SampleBundle\Entity;use Doctrine\ORM\Mapping as ORM;use Symfony\Component\Validator\Constraints as Assert;/** * Article * * @ORM\Table() * @ORM\Entity(repositoryClass="Symfony\Bundle\SampleBundle\Entity\ArticleRepository") */class Article{  /**   * @var integer   *   * @ORM\Column(name="id", type="integer")   * @ORM\Id   * @ORM\GeneratedValue(strategy="AUTO")   */  private $id;  /**   * @var string   * @Assert\NotBlank(message="標題不可為空白")   * @Assert\Length(   *   max=200,   *   maxMessage="標題不能超過200個字"   * )   * @ORM\Column(name="title", type="string", length=200)   */  private $title;  /**   * @var string   *   * @Assert\NotBlank(message="文章內容不可為空白")   * @ORM\Column(name="content", type="text")   */  private $content;  /**   * @var string   *   * @ORM\Column(name="author", type="string", length=20,nullable=true)   */  private $author;  /**   * Get id   *   * @return integer   */  public function getId()  {    return $this->id;  }  /**   * Set title   *   * @param string $title   * @return Article   */  public function setTitle($title)  {    $this->title = $title;    return $this;  }  /**   * Get title   *   * @return string   */  public function getTitle()  {    return $this->title;  }  /**   * Set content   *   * @param string $content   * @return Article   */  public function setContent($content)  {    $this->content = $content;    return $this;  }  /**   * Get content   *   * @return string   */  public function getContent()  {    return $this->content;  }  /**   * Set author   *   * @param string $author   * @return Article   */  public function setAuthor($author)  {    $this->author = $author;    return $this;  }  /**   * Get author   *   * @return string   */  public function getAuthor()  {    return $this->author;  }}

然後執行同步資料庫的操作:

$ php app/console doctrine:schema:update --forceUpdating database schema...Database schema updated successfully! "1" queries were executed

增刪改查

好了,我們來做一個針對文章的增刪改查操作。首先請執行下面的命令:

$ php app/console generate:doctrine:crud Welcome to the Doctrine2 CRUD generatorThis command helps you generate CRUD controllers and templates.First, you need to give the entity for which you want to generate a CRUD.You can give an entity that does not exist yet and the wizard will helpyou defining it.You must use the shortcut notation like AcmeBlogBundle:Post.The Entity shortcut name: SymfonySampleBundle:ArticleBy default, the generator creates two actions: list and show.You can also ask it to generate "write" actions: new, update, and delete.Do you want to generate the "write" actions [no]? yesDetermine the format to use for the generated CRUD.Configuration format (yml, xml, php, or annotation) [annotation]: ymlDetermine the routes prefix (all the routes will be "mounted" under thisprefix: /prefix/, /prefix/new, ...).Routes prefix [/article]: /article Summary before generationYou are going to generate a CRUD controller for "SymfonySampleBundle:Article"using the "yml" format.Do you confirm generation [yes]? yes CRUD generationGenerating the CRUD code: OKGenerating the Form code: OK You can now start using the generated code!

然後請編輯DefaultController.php中的indexAction如下:

/** * @Route("/",name="welcome") * @Template() */public function indexAction(){  return array();}

編輯Resource/views/Default/index.html.twig內容如下:

文章管理

讓我們看看神奇的事情,啟動內建的測試伺服器:

$php app/console server:run

好了,我們已經完成了這十分鐘的部落格,一切的代碼都在Controller/ArticleController.php,Form/ArticleType.php,Resource/views/Article/*.html.twig中,我們已經完成了最基本的文章管理功能。當然在你熟悉Symfony以後,未必需要完全依靠Symfony幫你產生這些增刪改查操作,可是起碼Symfony用一個命令讓一切都先運行起來了,這不就是我們所要的原型嗎?

本文永久地址:http://blog.it985.com/5133.html
本文出自 IT985部落格 ,轉載時請註明出處及相應連結。

更多關於PHP架構相關內容感興趣的讀者可查看本站專題:《php優秀開發架構總結》,《codeigniter入門教程》,《CI(CodeIgniter)架構進階教程》,《Yii架構入門及常用技巧總結》及《ThinkPHP入門教程》

希望本文所述對大家基於Symfony架構的PHP程式設計有所協助。

您可能感興趣的文章:

  • 高效能PHP架構Symfony2經典入門教程
  • PHP的Symfony和CodeIgniter架構的Nginx重寫規則配置
  • Symfony資料校正方法執行個體分析
  • symfony表單與頁面實現技巧
  • Symfony頁面的基本建立執行個體詳解
  • 如何在symfony中匯出為CSV檔案中的資料
  • Symfony2 session用法執行個體分析

http://www.bkjia.com/PHPjc/1098686.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1098686.htmlTechArticleSymfony學習十分鐘入門經典教程,symfony十分鐘 Symfony是一個強大的基於PHP的Web開發架構,在這裡我們用十分鐘的時間來做一個簡單的增刪改查...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.