Symfony2.5快速開發

前言:sf2是一個重量級框架,基本上能做http的任何事情,使用靈活的配置直接使用通用代碼以減少開發,基於composer集成多個功能包,自身核心主要解決controller級相關問題。本指南主要面向有框架相關基礎的php中級程序員,推薦使用循環學習法學成sf2框架。

 

 

一、準備工作

1、服務器php5.4+mysql5.1+,並配置好web 網站 http://127.0.0.1/ 可訪問。

2php.ini裏設置:

[xdebug]

zend_extension = php_xdebug-2.2.5-5.5-vc11-nts-x86_64.dll

xdebug.max_nesting_level = 250

realpath_cache_size = 1024

3、下載sf

http://symfony.com/download?v=Symfony_Standard_Vendors_2.5.6.zip

http://zyme.name/Symfony_Standard_Vendors_2.5.6.zip

4、開發佈署:爲了方便訪問,解壓sf包到http://127.0.0.1/web根目錄即可,然後能訪問 http://127.0.0.1/Symfony/web/config.php 查看是否安裝合格,點這頁的config...online進行系統簡單安裝,然後 http://127.0.0.1/Symfony/web/app_dev.php/ 就是首頁。

5、以後本文 -/ 代指 http://127.0.0.1/Symfony/web/app_dev.php/ 路徑, ~/ 代指硬盤中 .../ Symfony/ 目錄。

 

6、歡迎頁面上的要點:

右上角的搜索可以搜索到sf官網上的文檔內容,

RUN THE DEMO可以看到默認演示網站(這是示例,可以研究),其源代碼在~/src/Acme裏,

頁腳是debug工具條,裏面重點關注request,logs,routing,doctrine

7、相關參考:

http://symfony.com/doc/current/quick_tour/the_big_picture.html

http://symfony.com/doc/current/index.html

http://firehare.blog.51cto.com/809276/592385

http://symfony.cn/docs/quick_tour/index.html

http://www.howzhi.com/course/5389/

http://www.chrisyue.com/posts/270.translation-create-your-own-framework-on-top-of-the-symfony2-components-index

http://firehare.blog.51cto.com/809276/703599

 

 

二、博客實例.準備.註冊

1、本例實現簡單的blog系統,功能要點爲:註冊,登錄,文章列表,分頁,錄入,修改等。知識要點爲:包,控制器,路由,數據層,表單,視圖等。

2、數據庫,sf2支持從ormmysql,這裏使用我們的習慣:從mysqlorm,執行mysql代碼,產生一些簡單的blog系統數據表

CREATE TABLE `user` (

  `user_id` int(9) unsigned NOT NULL AUTO_INCREMENT COMMENT '用戶ID',

  `username` varchar(20) NOT NULL COMMENT '用戶名稱',

  `password` varchar(32) NOT NULL COMMENT '登錄密碼',

  PRIMARY KEY (`user_id`),

  UNIQUE KEY `username` (`username`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='會員表';

 

CREATE TABLE `post` (

  `post_id` int(9) unsigned NOT NULL AUTO_INCREMENT COMMENT '文章ID',

  `user_id` int(9) unsigned NOT NULL COMMENT '用戶ID',

  `title` varchar(250) NOT NULL COMMENT '文章標題',

  `content` text NOT NULL COMMENT '文章內容',

  `created` datetime NOT NULL COMMENT '創建時間',

  PRIMARY KEY (`post_id`),

  KEY `user_id` (`user_id`),

  CONSTRAINT `post_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='文章表';

3、創建site包,到 ~/ 目錄下運行命令

php app/console generate:bundle --namespace=Site/BlogBundle

在以下提示後輸入相關值,即使用註釋作配置,並創建目錄結構,其它默認回車即可

Configuration format (yml, xml, php, or annotation): annotation

Do you want to generate the whole directory structure [no]? yes

這會產生一些默認文件到~/src/Site/BlogBundle目錄,同時訪問 - /hello/zyme 有內容顯示。

4、映射mysql表到entity文件,到 ~/ 目錄下運行命令

php app/console doctrine:mapping:import SiteBlogBundle yml

這會產生兩個文件到~/src/Site/BlogBundle/Resources/config/doctrine目錄。

再到 ~/ 目錄下運行命令

php app/console doctrine:mapping:convert annotation src

這會產生兩個文件到~/src/Site/BlogBundle/Entity目錄。

再到 ~/ 目錄下運行命令

php app/console doctrine:generate:entities SiteBlogBundle

這會自動補充完entityorm屬性的getset方法。這兩個文件即是mysqlModel

5、實現會員表單模型,到 ~/ 目錄下運行命令

php app/console generate:doctrine:form SiteBlogBundle:User

這會產生UserType.php文件到~/src/Site/BlogBundle/Form目錄。這是會員formModel

6、實現文章表單模型,到 ~/ 目錄下運行命令

php app/console generate:doctrine:form SiteBlogBundle:Post

這會產生PostType.php文件到~/src/Site/BlogBundle/Form目錄。這是文章formModel

7、實現會員表單控制器,裏面有兩個功能:註冊和登錄,到 ~/ 目錄下運行命令

php app/console generate:controller --controller=SiteBlogBundle:User

在以下提示後輸入相關值,即創建了兩個action及其route,其它默認回車即可

New action name (press <return> to stop adding actions): registerAction

Action route [/register]: /user/register

New action name (press <return> to stop adding actions): loginAction

Action route [/login]: /user/login

這會自動產生~/src/Site/BlogBundle/Controller/UserController.php文件,即userController

同時自動產生~/src/Site/BlogBundle/Resources/views/User下模板文件,即userView

8、完善會員表單控制器registerAction方法,編輯~/src/....../UserController.php文件

class前面增加

use Site\BlogBundle\Entity\User;

use Site\BlogBundle\Form\UserType;

並修改registerAction()

    public function registerAction()

    {

                   $form = $this->createForm(new UserType(), new User());

                   $form->add('確定', 'submit');

                   $form->handleRequest($this->getRequest());

                   if ($form->isValid())

                   {

                            $em = $this->getDoctrine()->getManager();

                            $em->persist($form->getData());

                            $em->flush();

                            exit('OK.'.__METHOD__);

                   }

        return ['form' => $form->createView()];

         }

 

9、完善會員註冊表單視圖,編輯~/src/...... /views/User下模板文件爲

{% extends "::base.html.twig" %}

{% block body %}

    {{ form(form) }}

{% endblock %}

10、訪問網頁 -/user/register ,註冊一個會員,返回ok即可。

 

 

三、博客實例.登錄

1、系統對登錄的處理,需要幾個要點配合:防火牆,訪問控制,用戶接口,登錄表單等。

2、用戶接口,擴充 ~/src/Site/BlogBundle/Entity/User.php 實現 UserInterface 接口

use Symfony\Component\Security\Core\User\UserInterface;

class User implements UserInterface

{

    #......# 增加的對UserInterface 接口的實現方法

    public function getRoles()

    {

        return array('ROLE_USER');

    }

    public function getSalt() { }

    public function eraseCredentials() { }

}

3、網站配置,修改 ~/app/config/security.yml 文件內應有以下設置

security:

    encoders:

        Site\BlogBundle\Entity\User: plaintext

    providers:

        site_blog_user:

            entity: { class: SiteBlogBundle:User, property: username }

    firewalls:

        dev:

            pattern:  ^/(_(profiler|wdt)|css|images|js)/

            security:  false

        site_blog_pass_area:

            pattern:   ^/user/(login|register)$

            security:  false

        site_blog_secured_area:

            pattern:   ^/

            provider:  site_blog_user

            http_basic:

                realm: "Secured Area"

    access_control:

        - { path: ^/user/(login|register)$, roles: IS_AUTHENTICATED_ANONYMOUSLY }

        - { path: ^/, roles: ROLE_USER }

此時,訪問 -/user/register 時不會提示輸入密碼框,訪問其它如 -/ 時,都會提示需要密碼。

4、以上配置,登錄使用的是http認證,可以修改爲常用的登錄表單認證,方法見官方文檔。

 

 

三、博客實例.文章增加.修改.刪除

 

 

四、博客實例.文章列表分頁

 

五、多語言

1、修改app配置文件,~/app/config/config.yml

framework:

    translator:      { fallback: "%locale%" }

2、增加各種語言的譯文文件,比如這裏支持en(英文) / zh(簡體中文) / zh-tw(繁體中文),在....../Resources/translations目錄下,創建三個文件messages.en.yml/messages.zh.yml

#文件messages.en.yml的內容

sf.good: Symfony is good

#文件messages.zh.yml的內容

sf.good: 簡體中文

#文件messages.zh-tw.yml的內容

sf.good: 中文繁體

3、在控制器裏使用多語言結果,比如-/hello/zyme對應的控制器indexAction修改爲

    public function indexAction($name)

    {

                   $this->getRequest()->setLocale('en'); // 分別設置爲en/zh/zh-tw不同翻譯結果

                   $name = $this->get('translator')->trans('sf.good');

        return array('name' => $name);

    }

然後訪問 -/hello/zyme 可以看到不同的翻譯結果

4、或者,不在控制器裏使用多語言結果,也可以在view文件裏進行翻譯輸出

{% trans %}sf.good{% endtrans %}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章