


Detailed explanation of project creation and template setting examples of Symfony2 framework, symfony2 framework_PHP tutorial
Detailed explanation of project creation and template setting examples of Symfony2 framework, symfony2 framework
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. 简洁:想想看要打<?php ?>, 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.
让我们看一下头部文件
复制代码 代码如下:
{% 标签中即不是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标签{{, 这是一个输出(说些什么)标签。
复制代码 代码如下:
这个标签用于输出变量或者表达式, 上面例子输出了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程序设计有所帮助。
您可能感兴趣的文章:
- Symfony2使用Doctrine进行数据库查询方法实例总结
- Symfony2实现从数据库获取数据的方法小结
- Symfony2创建页面实例详解
- Symfony2之session与cookie用法小结
- Symfony2框架学习笔记之表单用法详解
- Symfony2学习笔记之插件格式分析
- Symfony2学习笔记之系统路由详解
- Symfony2学习笔记之控制器用法详解
- Symfony2学习笔记之模板用法详解
- Symfony2开发之控制器用法实例分析
- Symfony2安装第三方Bundles实例详解
- Symfony2使用第三方库Upload制作图片上传实例详解
- Symfony2联合查询实现方法

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



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

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

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

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

Regarding PPT masking, many people must be unfamiliar with it. Most people do not understand it thoroughly when making PPT, but just make it up to make what they like. Therefore, many people do not know what PPT masking means, nor do they understand it. I know what this mask does, and I don’t even know that it can make the picture less monotonous. Friends who want to learn, come and learn, and add some PPT masks to your PPT pictures. Make it less monotonous. So, how to add a PPT mask? Please read below. 1. First we open PPT, select a blank picture, then right-click [Set Background Format] and select a solid color. 2. Click [Insert], word art, enter the word 3. Click [Insert], click [Shape]

PyCharm is a powerful Python integrated development environment (IDE) that provides rich functions to help developers write and manage Python projects more efficiently. In the process of developing projects using PyCharm, sometimes we need to delete some projects that are no longer needed to free up space or clean up the project list. This article will detail how to delete projects in PyCharm and provide specific code examples. How to delete a project Open PyCharm and enter the project list interface. In the project list,

IDEA (IntelliJIDEA) is a powerful integrated development environment that can help developers develop various Java applications quickly and efficiently. In Java project development, using Maven as a project management tool can help us better manage dependent libraries, build projects, etc. This article will detail the basic steps on how to create a Maven project in IDEA, while providing specific code examples. Step 1: Open IDEA and create a new project Open IntelliJIDEA

C++ template specializations affect function overloading and rewriting: Function overloading: Specialized versions can provide different implementations of a specific type, thus affecting the functions the compiler chooses to call. Function overriding: The specialized version in the derived class will override the template function in the base class, affecting the behavior of the derived class object when calling the function.
