


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. 简洁:想想看要打, 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 id="block-blog-title-a-href-symfony-a-endblock">{% block blog_title %}<a href="#">symfony</a>{% endblock %}</h2> <h3 id="block-blog-tagline-a-href-creating-a-blog-in-Symfony-a-endblock">{% 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联合查询实现方法

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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