


Detailed explanation of creating projects and setting templates in Symfony2 framework
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. 简洁:想想看要打, 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='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"> <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 '::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标签{{, 这是一个输出(说些什么)标签。
<link href="{{ asset('css/screen.css') }}" 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: '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
相关推荐:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Fermat's last theorem, about to be conquered by AI? And the most meaningful part of the whole thing is that Fermat’s Last Theorem, which AI is about to solve, is precisely to prove that AI is useless. Once upon a time, mathematics belonged to the realm of pure human intelligence; now, this territory is being deciphered and trampled by advanced algorithms. Image Fermat's Last Theorem is a "notorious" puzzle that has puzzled mathematicians for centuries. It was proven in 1993, and now mathematicians have a big plan: to recreate the proof using computers. They hope that any logical errors in this version of the proof can be checked by a computer. Project address: https://github.com/riccardobrasca/flt

Share the simple and easy-to-understand PyCharm project packaging method. With the popularity of Python, more and more developers use PyCharm as the main tool for Python development. PyCharm is a powerful integrated development environment that provides many convenient functions to help us improve development efficiency. One of the important functions is project packaging. This article will introduce how to package projects in PyCharm in a simple and easy-to-understand way, and provide specific code examples. Why package projects? Developed in Python

PyCharm is a powerful Python integrated development environment that provides a wealth of development tools and environment configurations, allowing developers to write and debug code more efficiently. In the process of using PyCharm for Python project development, sometimes we need to package the project into an executable EXE file to run on a computer that does not have a Python environment installed. This article will introduce how to use PyCharm to convert a project into an executable EXE file, and give specific code examples. head

Title: Learn more about PyCharm: An efficient way to delete projects. In recent years, Python, as a powerful and flexible programming language, has been favored by more and more developers. In the development of Python projects, it is crucial to choose an efficient integrated development environment. As a powerful integrated development environment, PyCharm provides Python developers with many convenient functions and tools, including deleting project directories quickly and efficiently. The following will focus on how to use delete in PyCharm

Title: Realme Phone Beginner’s Guide: How to Create Folders on Realme Phone? In today's society, mobile phones have become an indispensable tool in people's lives. As a popular smartphone brand, Realme Phone is loved by users for its simple and practical operating system. In the process of using Realme phones, many people may encounter situations where they need to organize files and applications on their phones, and creating folders is an effective way. This article will introduce how to create folders on Realme phones to help users better manage their phone content. No.

This article will interest you if you are interested in using GIMP for pixel art creation on Windows. GIMP is a well-known graphics editing software that is not only free and open source, but also helps users create beautiful images and designs easily. In addition to being suitable for beginners and professional designers alike, GIMP can also be used to create pixel art, a form of digital art that utilizes pixels as the only building blocks for drawing and creating. How to Create Pixel Art in GIMP Here are the main steps to create pixel pictures using GIMP on a Windows PC: Download and install GIMP, then launch the application. Create a new image. Resize width and height. Select the pencil tool. Set the brush type to pixels. set up

Many friends expressed that they want to know how to create a family in Gree+ software. Here is the operation method for you. Friends who want to know more, come and take a look with me. First, open the Gree+ software on your mobile phone and log in. Then, in the options bar at the bottom of the page, click the "My" option on the far right to enter the personal account page. 2. After coming to my page, there is a "Create Family" option under "Family". After finding it, click on it to enter. 3. Next jump to the page to create a family, enter the family name to be set in the input box according to the prompts, and click the "Save" button in the upper right corner after entering it. 4. Finally, a "save successfully" prompt will pop up at the bottom of the page, indicating that the family has been successfully created.

How to use Highcharts to create a Gantt chart requires specific code examples. Introduction: The Gantt chart is a chart form commonly used to display project progress and time management. It can visually display the start time, end time and progress of the task. Highcharts is a powerful JavaScript chart library that provides rich chart types and flexible configuration options. This article will introduce how to use Highcharts to create a Gantt chart and give specific code examples. 1. Highchart
