Home >Backend Development >PHP Tutorial >Detailed explanation of project creation and template setting examples of Symfony2 framework, symfony2 framework_PHP tutorial
This article describes the method of project creation and template setting of Symfony2 framework through examples. Share it with everyone for your reference, the details are as follows:
Environment preparation and overview
Accustomed to using netbean editor in windows and using virtualbox virtual centos system, pre-install nginx php-fpm mysql, of course apache is also a good choice, use http://symfony as the development domain name on windows and centos.
1. Download and environment settings
1. How to establish a development environment on centos will not be described in detail. Of course, you can also establish a development environment on windows.
2. Regarding using symfony instead of 127.0.0.1 to modify the /etc/hosts file in the liunx system and the C:WindowsSystem32driversetchost file in the win7 system (needs to be opened with administrator privileges)
Just add content similar to IP alias 1 and alias 2, such as:
Copy code The code is as follows: # /etc/hosts 127.0.0.1 symblog dev symfony
3. Download symfony2 manually, or you can refer to this page to install it with Composer. http://symfony.com/doc/current/book/installation.html
The only thing to note is that the app/cache and app/logs directories need to be set to 777 permissions. This problem should not exist in the windows development environment.
4. Modify the apache or nginx configuration file symfony domain name to point to the web directory of the downloaded symfony file.
At this point, you should be able to access the default page of symfony through http://symfony/app_dev.php. There are several demos you can refer to and learn from.
app_dev.php loads a development toolbar below by default, which displays some information about the current page, which greatly facilitates program debugging. It will only be displayed when the environment variable is dev.
5. When using composer to install, you will be prompted to output mysql and other related information. If you need to modify this information, or directly download the file, you can enter the "Configure" page to make relevant settings.
Bundles (maybe called packages, bundles, assemblies, or projects, let’s use English) are the basic stuff of symfony, which are reusable code packages shared one by one. Even symfony itself is as a bundles run. Including controllers, modules, templates, and even images, js, css style sheets and other resources. It’s a very messy thing. Different bundles use the namespace after php5.3. Most cpenal and da virtual hosts seem to only have php5.2 version, and symfony2 cannot be run.
2. Create a Bundle
In the following example, a blog will be created. Symfony provides a large number of tools to quickly create projects. For example, we can use it to quickly create a basic blog bundle.
Copy code The code is as follows: php app/console generate:bundle –namespace=Blogger/BlogBundle –format=yml
Just use all the default settings after running it. We can easily create the basic controllers, modules and templates we need. Contains the following behaviors:
Register Bundles
All bundles used in symfony need to be registered first. Some bundles will only be used in development and test environments (dev or test), such as the development toolbar mentioned above. The following code snippet shows how the bundle creation command works Register the BloggerBlogBundle bundle.
// app/AppKernel.php class AppKernel extends Kernel { public function registerBundles() { $bundles = array( // .. new Blogger\BlogBundle\BloggerBlogBundle(), ); // .. return $bundles; } // .. } }
Routing
As a framework, the routing function is created in app/config/routing.yml by the bundler creator. Symfony uses yml format to save configuration information.
Copy code The code is as follows:
# app/config/routing.yml
BloggerBlogBundle:
resource: "@BloggerBlogBundle/Resources/config/routing.yml"
prefix: /
The prefix option allows us to place it in subdirectories such as blog, news, etc.
File
In addition to the above configuration files, most other files are generated in the src directory, like most MVC frameworks. The Blogger directory is generated under src, and there is a BlogBundle subdirectory that stores various related stuff. The difference is that a directory similar to blogger corresponds to the PHP namespace.
Default Controller
The Bundle generator generates the default controller under src. A simple hello can be seen by visiting: http://symfony/app_dev.php/hello/world. About how this page was generated:
Routing
It’s still routing. The difference is that the previous routing is registered and used in the entire program. The routing here controls the use of specific pages. src/Blogger/BlogBundle/Resources/config/routing.yml controls BloggerBlogBundle and contains the following program snippets. :
Copy code The code is as follows:
# src/Blogger/BlogBundle/Resources/config/routing.yml
BloggerBlogBundle_homepage:
pattern: /hello/{name}
defaults: { _controller: BloggerBlogBundle:Default:index }
参数: 进行url检测, 符合/hello/{name}结构的任意值将被赋予给{name},
方式: 没有对形式进行限制, 理论可以put, get, post, delete所有的操作都可以进行。
后续: 如果符合以上两条, 那么{name}将会传导至特定文件, 以上为src/Blogger/BlogBundle/Controller/DefaultController.php文件中的default控制器的index行为将被使用。
控制器
在默认生产的bundler中, 控制器行为相当简单, {name}参数被传入并被传出到模板文件:
// src/Blogger/BlogBundle/Controller/DefaultController.php namespace Blogger\BlogBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction($name) { return $this->render('BloggerBlogBundle:Default:index.html.twig', array('name' => $name)); } }
BloggerBlogBundle:Default:index.html.twig 会使用 BloggerBlogBundle views文件夹中 Default文件夹下面index.html.twig模板文件.
模板文件
打开上述模板文件, 非常简单的一句代码:
{# src/Blogger/BlogBundle/Resources/views/Default/index.html.twig #} Hello {{ name }}!
以上就是symfony的整个mvc流程, 这么多文件的作用只是输出一个 “hello world”. 理论上不用bundler创建器, 只是手动创建上述文件也可以实现相同效果。花费的时间就多了去了。
回到正题, 我们是创建博客系统, 所以不需要 hello world,
1.移除控制器 src/Blogger/BlogBundle/Controller/DefaultController.php
2.移除模板 src/Blogger/BlogBundle/Resources/views/Default/
3.最后移除路由 src/Blogger/BlogBundle/Resources/config/routing.yml
整个世界清静了。
三、让我们开始创建博客的主页
Twig的优点
在symfony中我们可以使用 Twig和php(这不是废话嘛)作为模板。使用Twig的以下优点:
1. 快: 是编绎过的php类, 可以占用更少的资源
2. 简洁:想想看要打add3a0846a89c578be00859a0f55a47a, Twig输入的内容要少很多。
3. 可继承: 非常cool的一个功能
4. 安全: 转义功能默认开启, 甚至还可以为重要代码提供沙盒功能。
5. 可扩展: 需要额外的定制功能, 可以随时扩展
更多内容, 请移步:http://twig.sensiolabs.org/
可继承是一个非常好的优点, 我们将使用三级继承结构来定制这个模板, 这将允许我们在三个不同层级修改模板, 方便自由定制。
主模板–level 1
<!– app/Resources/views/base.html.twig –> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html"; charset=utf-8" /> <title>{% block title %}symfony{% endblock %} – blog</title> <!–[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]–> {% block stylesheets %} <link href='http://fonts.googleapis.com/css?family=Irish+Grover' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=La+Belle+Aurore' rel='stylesheet' type='text/css'> <link href="{{ asset('css/screen.css') }}" type="text/css" rel="stylesheet" /> {% endblock %} <link rel="shortcut icon" href="{{ asset('favicon.ico') }}" /> </head> <body> <section id="wrapper"> <header id="header"> <div> {% block navigation %} <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </nav> {% endblock %} </div> <hgroup> <h2>{% block blog_title %}<a href="#">symfony</a>{% endblock %}</h2> <h3>{% block blog_tagline %}<a href="#">creating a blog in Symfony2</a>{% endblock %}</h3> </hgroup> </header> <section> {% block body %}{% endblock %} </section> <aside> {% block sidebar %}{% endblock %} </aside> <div id="footer"> {% block footer %} <a href="http://blog.dengruo.com/201309/1409">Symfony2 博客教程</a> {% endblock %} </div> </section> {% block javascripts %}{% endblock %} </body> </html>
上面代码在引入了一个js文件, 在ie9版本前的浏览器中实现html, 以及两个css文件导入google fronts.
这构成了网页的主要内容结构, 相当于drupal的html.tpl.php+page.tpl.php.
让我们看一下头部文件
复制代码 代码如下:b2386ffb911b14667cb8f0f91ea547a7{% block title %}blog{% endblock %} – symfony6e916e0f7d1e588d4f442bf645aedb2f
{% 标签中即不是html, 也不是php, 他是3个Twig标签中的一个, 用于执行某些动作。 这里可以找到完整的Twig控制动作用于这个标签。 回到当前代码, 是用于查找title的block并输出他, 如果没有则输出默认的symblo这个词。
Twig的可续承特性可以用于修改title, 我们可以在其它模板文件中重写它:
{% extends '::base.html.twig' %}
{% block title %}The blog title goes here{% endblock %}
上面代码首先继承了第一次定义这个block的文件, 然后修改它。 网站标题部分会输出 'The blog title goes here – symfony'。
一般而言, 我们引用模板文件时会采用bundle:controller:template, 但是以上代码并没有bundle 和controller, 不包含这两个字段会直接引用app/Resources/views/ 文件夹下面的文件。
在css样式表中, 我们可以发现另一个Twig标签{{, 这是一个输出(说些什么)标签。
复制代码 代码如下:822b544e7fc2bac7e51713e4fce9e4a7
这个标签用于输出变量或者表达式, 上面例子输出了asset函数的返回值, 这个函数提供可移植的方式来返回css,js, 图片的地址。
这个标签可以以特定格式输出我们想要内容, 比如时间:
复制代码 代码如下:{{ blog.created|date("d-m-Y") }}
全部过滤列表在 Twig 文档可以查到。
最后一个标签并没有在上述代码中出现, 它是{#, 只是一个注释标签
复制代码 代码如下:{# 注释内容可以输出在这里 #}
接下来我们将创建css样式表web/css/screen.css , 加入以下内容.
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{border:0;font-size:100%;font:inherit;vertical-align:baseline;margin:0;padding:0}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:before,blockquote:after,q:before,q:after{content:none}table{border-collapse:collapse;border-spacing:0} body { line-height: 1;font-family: Arial, Helvetica, sans-serif;font-size: 12px; width: 100%; height: 100%; color: #000; font-size: 14px; } .clear { clear: both; } #wrapper { margin: 10px auto; width: 1000px; } #wrapper a { text-decoration: none; color: #F48A00; } #wrapper span.highlight { color: #F48A00; } #header { border-bottom: 1px solid #ccc; margin-bottom: 20px; } #header .top { border-bottom: 1px solid #ccc; margin-bottom: 10px; } #header ul.navigation { list-style: none; text-align: right; } #header .navigation li { display: inline } #header .navigation li a { display: inline-block; padding: 10px 15px; border-left: 1px solid #ccc; } #header h2 { font-family: 'Irish Grover', cursive; font-size: 92px; text-align: center; line-height: 110px; } #header h2 a { color: #000; } #header h3 { text-align: center; font-family: 'La Belle Aurore', cursive; font-size: 24px; margin-bottom: 20px; font-weight: normal; } .main-col { width: 700px; display: inline-block; float: left; border-right: 1px solid #ccc; padding: 20px; margin-bottom: 20px; } .sidebar { width: 239px; padding: 10px; display: inline-block; } .main-col a { color: #F48A00; } .main-col h1, .main-col h2 { line-height: 1.2em; font-size: 32px; margin-bottom: 10px; font-weight: normal; color: #F48A00; } .main-col p { line-height: 1.5em; margin-bottom: 20px; } #footer { border-top: 1px solid #ccc; clear: both; text-align: center; padding: 10px; color: #aaa; }
Bundler模板–level 2
现在我们为blog bundler 创建模板, 创建src/Blogger/BlogBundle/Resources/views/layout.html.twig 并加入:
复制代码 代码如下:
{# src/Blogger/BlogBundle/Resources/views/layout.html.twig #}
{% extends '::base.html.twig' %}
{% block sidebar %}
Sidebar content
{% endblock %}
非常简单的代码,1. 继承了一级模板, 并且为博客内容特别定制了侧边栏, 很显然我们并不想博客的布局与其它页面一样。 类似drupal7中page–content-type.tpl.php模板, 定制了某一特殊类型内容的布局。
具体页面布局–level 3
这个阶段已经涉及到创建具体页面, 所以需要先创建控制器src/Blogger/BlogBundle/Controller/PageController.php
// src/Blogger/BlogBundle/Controller/PageController.php namespace Blogger\BlogBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class PageController extends Controller { public function indexAction() { return $this->render('BloggerBlogBundle:Page:index.html.twig'); } }
然后创建相应的Twig文件: src/Blogger/BlogBundle/Resources/views/Page/index.html.twig
复制代码 代码如下:
{# src/Blogger/BlogBundle/Resources/views/Page/index.html.twig #}
{% extends 'BloggerBlogBundle::layout.html.twig' %}
{% block body %}
Blog homepage
{% endblock %}
创建路由将首页引导到我们刚创建的页面:src/Blogger/BlogBundle/Resources/config/routing.yml
复制代码 代码如下:
# src/Blogger/BlogBundle/Resources/config/routing.yml
BloggerBlogBundle_homepage:
pattern: /
defaults: { _controller: BloggerBlogBundle:Page:index }
requirements:
_method: GET
再次访问 http://symfony/app_dev.php可以看见简单的首页。
四、再创建一个about页面
路由:在src/Blogger/BlogBundle/Resources/config/routing.yml中加入
复制代码 代码如下:
# src/Blogger/BlogBundle/Resources/config/routing.yml
BloggerBlogBundle_about:
pattern: /about
defaults: { _controller: BloggerBlogBundle:Page:about }
requirements:
_method: GET
当以get方式访问about页时执行位于BloggerBlogBundle命名空间的page控制器about动作。
控制器: 在src/Blogger/BlogBundle/Controller/PageController.php 于page控制器中加入about动作
复制代码 代码如下:
// src/Blogger/BlogBundle/Controller/PageController.php
// ..
public function aboutAction()
{
return $this->render('BloggerBlogBundle:Page:about.html.twig');
}
// ..
模板: 创建src/Blogger/BlogBundle/Resources/views/Page/about.html.twig 并加入相关页面文件
复制代码 代码如下:
{# src/Blogger/BlogBundle/Resources/views/Page/about.html.twig #}
{% extends 'BloggerBlogBundle::layout.html.twig' %}
{% block body %}
about page
{% endblock %}
简单的三个流程增加了关于页面:http://symfony/app_dev.php/about
希望本文所述对大家基于Symfony框架的PHP程序设计有所帮助。