Home  >  Article  >  Backend Development  >  Detailed explanation of creating projects and setting templates in Symfony2 framework

Detailed explanation of creating projects and setting templates in Symfony2 framework

*文
*文Original
2018-01-05 17:50:591777browse

This article mainly introduces the method of creating projects and template settings in the Symfony2 framework, and analyzes the specific steps and detailed implementation code of the Symfony2 framework in detail in the form of examples. Friends in need can refer to it. I hope it will be helpful to everyone.

Environment preparation and overview

Get used 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. Modify the /etc/hosts file in the liunx system, and modify the C:\Windows\System32\drivers\etc\host file in the win7 system (needs to be opened with administrator rights) )

Just add content similar to IP alias 1 and alias 2, such as:

# /etc/hosts 127.0.0.1 symblog dev symfony

3. Manually download symfony2.

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 symfony's default page 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. Only when the environment variable is dev will be displayed.

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, reusable code packages shared one by one, even symfony itself It is run as a bundle. 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 the basic bundle of a blog.

php app/console generate:bundle –namespace=Blogger/BlogBundle –format=yml

After running, all the default settings can be directly adopted. We can easily create the basic controllers, modules and templates we need. Contains the following behavior:

Register Bundles

All bundles used in symfony are required to be registered first. Some bundles will only be used in development and testing environments (dev or test), as mentioned above in the development toolbar. The following code snippet shows how the bundle creation command registers 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.

# 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.
Files
Except for 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. Regarding how this page is generated:

routing

is still routing. The difference is that the previous routing is registered and used in the entire program. The routing here controls the specific page. Use, src/Blogger/BlogBundle/Resources/config/routing.yml to control BloggerBlogBundle, including the following program fragments:

# src/Blogger/BlogBundle/Resources/config/routing.yml
BloggerBlogBundle_homepage:
pattern: /hello/{name}
defaults: { _controller: BloggerBlogBundle:Default:index }

Parameters: For url detection, any value that matches the /hello/{name} structure will be Assigned to {name},
method: There is no restriction on the form. In theory, all operations of put, get, post, and delete can be performed.
Follow-up: If the above two items are met, then {name} will be transferred to a specific file, and the index behavior of the default controller in the src/Blogger/BlogBundle/Controller/DefaultController.php file will be used.

Controller

In the default production bundler, the controller behavior is quite simple, the {name} parameter is passed in and out to the template file:

// 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 will use the index.html.twig template file under the Default folder in the BloggerBlogBundle views folder.

Template file

Open the above template file, a very simple code:

{# 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. 简洁:想想看要打bb9bd6d87db7f8730c53cb084e6b4d2d, Twig输入的内容要少很多。

3. 可继承: 非常cool的一个功能

4. 安全: 转义功能默认开启, 甚至还可以为重要代码提供沙盒功能。

5. 可扩展: 需要额外的定制功能, 可以随时扩展

可继承是一个非常好的优点, 我们将使用三级继承结构来定制这个模板, 这将允许我们在三个不同层级修改模板, 方便自由定制。

主模板–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=&#39;http://fonts.googleapis.com/css?family=Irish+Grover&#39; rel=&#39;stylesheet&#39; type=&#39;text/css&#39;>
<link href=&#39;http://fonts.googleapis.com/css?family=La+Belle+Aurore&#39; rel=&#39;stylesheet&#39; type=&#39;text/css&#39;>
<link href="{{ asset(&#39;css/screen.css&#39;) }}" type="text/css" rel="stylesheet" />
{% endblock %}
<link rel="shortcut icon" href="{{ asset(&#39;favicon.ico&#39;) }}" />
</head>
<body>
<section id="wrapper">
<header id="header">
<p>
{% 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 %}
</p>
<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>
<p id="footer">
{% block footer %}
<a href="http://blog.dengruo.com/201309/1409">Symfony2 博客教程</a>
{% endblock %}
</p>
</section>
{% block javascripts %}{% endblock %}
</body>
</html>

上面代码在引入了一个js文件, 在ie9版本前的浏览器中实现html, 以及两个css文件导入google fronts.
这构成了网页的主要内容结构, 相当于drupal的html.tpl.php+page.tpl.php.
让我们看一下头部文件

<title>{% block title %}blog{% endblock %} – symfony</title>

{% 标签中即不是html, 也不是php, 他是3个Twig标签中的一个, 用于执行某些动作。 这里可以找到完整的Twig控制动作用于这个标签。 回到当前代码, 是用于查找title的block并输出他, 如果没有则输出默认的symblo这个词。
Twig的可续承特性可以用于修改title, 我们可以在其它模板文件中重写它:

{% extends &#39;::base.html.twig&#39; %}
{% 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标签{{, 这是一个输出(说些什么)标签。

<link href="{{ asset(&#39;css/screen.css&#39;) }}" type="text/css" rel="stylesheet" />

这个标签用于输出变量或者表达式, 上面例子输出了asset函数的返回值, 这个函数提供可移植的方式来返回css,js, 图片的地址。

这个标签可以以特定格式输出我们想要内容, 比如时间:

{{ blog.created|date("d-m-Y") }}

全部过滤列表在 Twig 文档可以查到。

最后一个标签并没有在上述代码中出现, 它是{#, 只是一个注释标签

{# 注释内容可以输出在这里 #}

接下来我们将创建css样式表web/css/screen.css , 加入以下内容.

html,body,p,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: &#39;Irish Grover&#39;, cursive; font-size: 92px; text-align: center; line-height: 110px; }
#header h2 a { color: #000; }
#header h3 { text-align: center; font-family: &#39;La Belle Aurore&#39;, 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 &#39;::base.html.twig&#39; %}
{% 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(&#39;BloggerBlogBundle:Page:index.html.twig&#39;);
}
}

然后创建相应的Twig文件: src/Blogger/BlogBundle/Resources/views/Page/index.html.twig

{# src/Blogger/BlogBundle/Resources/views/Page/index.html.twig #}
{% extends &#39;BloggerBlogBundle::layout.html.twig&#39; %}
{% 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(&#39;BloggerBlogBundle:Page:about.html.twig&#39;);
}
// ..

模板: 创建src/Blogger/BlogBundle/Resources/views/Page/about.html.twig 并加入相关页面文件

{# src/Blogger/BlogBundle/Resources/views/Page/about.html.twig #}
{% extends &#39;BloggerBlogBundle::layout.html.twig&#39; %}
{% block body %}
about page
{% endblock %}

简单的三个流程增加了关于页面:http://symfony/app_dev.php/about

相关推荐:

Detailed explanation of how Symfony obtains request parameters in templates and behaviors

Detailed explanation of the usage of Symfony template shortcut variables

Brief description of Symfony core classes

The above is the detailed content of Detailed explanation of creating projects and setting templates in Symfony2 framework. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn