Symfony2 framework for creating projects and template setting instances
This example describes how to create a project and set a template in the Symfony2 framework. We will share this with you for your reference. The details are as follows:
Environment preparation and overview
I used to use the netbean editor in windows and the virtualbox virtual centos system. I preinstalled nginx + php-fpm + mysql. Of course, apache is also a good choice, using http: // symfony serves as the development domain name on windows and centos.
1. Download and Environment Settings
1. How to create a development environment on centos is not described in detail. Of course, you can also create a development environment on windows.
2. modify the/etc/hosts file in liunx system instead of 127.0.0.1 using symfony, and modify the C: \ Windows \ System32 \ drivers \ etc \ host file in win7 system (which must be opened with administrator privileges)
Add content similar to IP alias 1 and alias 2, for example:
Copy codeThe Code is as follows: #/etc/hosts 127.0.0.1 symblog dev symfony
3. manually download symfony2. You can also refer to this page to use Composer for installation. Http://symfony.com/doc/current/book/installation.html
The only thing to note is that the app/cache and app/logs directories must be set to 777 permissions. This problem should not occur in the windows development environment.
4. Modify the symfony domain name of apache or nginx configuration file to point to the web directory of the downloaded symfony file.
In this case, you can access the default page of symfony through http: // symfony/app_dev.php. You can refer to several demos for more information.
App_dev.php loads a development toolbar under by default and displays some information on the current page, which greatly facilitates program debugging and is only displayed when the environment variable is dev.
5. When you use composer for installation, you will be prompted to output mysql and other related information. To modify the information or directly download the file, you can go to the "Configure" page to perform relevant settings.
Bundles (which can be called a package, bundle, assembly, or project) is the basic concept of symfony. It shares reusable code encapsulation one by one, even symfony runs as a bundles. Including controllers, modules, templates, images, js, css style sheets, and other resources. The difference between different bundles and namespaces after php5.3 is very messy. Most cpenal and da virtual hosts only have php5.2 and cannot run symfony2.
2. Create a Bundle
In the following example, we will create a blog. Symfony provides a large number of tools to quickly create a project. For example, we can use it to quickly create a basic bundle for a blog.
Copy codeThe Code is as follows: php app/console generate: bundle-namespace = Blogger/BlogBundle-format = yml
You can directly use all the default settings after running. You can easily create the required basic controllers, modules, and templates. Includes the following behaviors:
Register Bundles
All bundles used in symfony must be registered first. Some bundles will only be used in the development and testing environment (dev or test), as mentioned above. the broken code below shows how the bundles creation command registers the bundle of BloggerBlogBundle.
// app/AppKernel.phpclass AppKernel extends Kernel {public function registerBundles() {$bundles = array(// ..new Blogger\BlogBundle\BloggerBlogBundle(),);// .. return $bundles; } // ..}}
Routing
As a framework, the routing function is created by the bundler Creator in app/config/routing. yml, and symfony saves configuration information in yml format.
Copy codeThe 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 and news.
File
In addition to the preceding configuration files, most other files are generated in the src directory, just like most mvc frameworks. The Blogger directory is generated under src, And the BlogBundle sub-directory stores various related things. The difference is that the directory similar to blogger corresponds to the php namespace.
Default Controller
The Bundle generator generates the default Controller under src. Visit: http: // symfony/app_dev.php/hello/world to see simple greetings. How to generate this page:
Routing
Or 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 fragments:
Copy codeThe Code is as follows:
# Src/Blogger/BlogBundle/Resources/config/routing. yml
BloggerBlogBundle_homepage:
Pattern:/hello/{name}
Defaults: {_ controller: BloggerBlogBundle: Default: index}
Parameter: Performs url detection. Any value conforming to the/hello/{name} structure will be assigned to {name },
Method: there is no restriction on the form. In theory, you can perform put, get, post, and delete operations.
Later: if the above two conditions are met, {name} will be transmitted to a specific file. The above conditions are src/Blogger/BlogBundle/Controller/DefaultController. the index behavior of the default controller in the PHP file will be used.
Controller
In the default production bundler, the Controller behavior is quite simple. The {name} parameter is passed in and passed out to the template file:
// src/Blogger/BlogBundle/Controller/DefaultController.phpnamespace 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 uses the Default file index.html. twig in the BloggerBlogBundle views folder.
Template File
Open the above template file with a very simple code:
{# src/Blogger/BlogBundle/Resources/views/Default/index.html.twig #}Hello {{ name }}!
The above is the entire mvc process of symfony. The role of so many files is only to output a "hello world". Theoretically, you do not need to create a bundler, but you can create the above files manually to achieve the same effect. It takes more time.
Back to the topic, we are creating a blog system, so we don't need hello world,
1. Remove the Controller src/Blogger/BlogBundle/Controller/DefaultController. php
2. Remove the src/Blogger/BlogBundle/Resources/views/Default/template/
3. Finally, remove the src/Blogger/BlogBundle/Resources/config/routing. yml route.
The whole world is quiet.
3. Let's start creating a blog homepage.
Advantages of Twig
In symfony, we can use Twig and php (this is not nonsense) as templates. Twig has the following advantages:
1. Fast: it is a compiled php class that can consume less resources.
2. Concise: Think about it. <? Php?>, There is much less Twig input.
3. Inheritance: a very cool Function
4. Security: the escape function is enabled by default and can even provide sandbox functions for important codes.
5. Scalability: Additional custom functions are required and can be expanded at any time.
For more information, see: http://twig.sensiolabs.org/
Inheritance is a very good advantage. We will use a three-level inheritance structure to customize this template, which will allow us to modify the template at three different levels for convenient customization.
Master template-level 1
<! -App/Resources/views/base.html. twig-> <! DOCTYPE html>
The above Code introduces a js file, implements html in the browser before ie9, and imports two css files into google fronts.
This constitutes the main content structure of the webpage, which is equivalent to drupal's html. tpl. php + page. tpl. php.
Let's take a look at the header file.
Copy codeThe Code is as follows: <title >{% block title %} blog {% endblock %}-symfony </title>
{% Tag is neither html nor php. It is one of the three Twig tags and is used to execute certain actions. Here we can find the complete Twig control action for this tag. Return to the current Code, which is used to find the block of the title and output it. If not, the default symblo word is output.
The resumable feature of Twig can be used to modify the title. We can rewrite it in other template files:
{% Extends ': base.html. twig' %}
{% Block title %} The blog title goes here {% endblock %}
The above code first inherits the file that defines the block for the first time, and then modifies it. The 'blog title goes here-symfony 'is output in The website title section '.
Generally, we use bundle: controller: template When referencing a template file, but the above Code does not include bundle and controller, files in the app/Resources/views/folder are directly referenced if these fields are not included.
In the css style sheet, we can find another Twig tag {, which is an output tag (what to say.
Copy codeThe Code is as follows: <link href = "{asset ('css/screen.css ')}" type = "text/css" rel = "stylesheet"/>
This label is used to output variables or expressions. In the above example, the returned values of the asset function are output. This function provides a portable method to return the addresses of css, js, and images.
This label can output the desired content in a specific format, such as time:
Copy codeCode: {blog. created | date ("d-m-Y ")}}
The list of all filters can be found in the Twig document.
The last tag does not appear in the above Code. It is {#, just a comment tag.
Copy codeThe Code is as follows: {# The comment content can be output here #}
Next we will create a css style sheet web/css/screen.css and add the following content.
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 template-level 2
Now we create a template for blog bundler, create src/Blogger/BlogBundle/Resources/views/layout.html. twig, and add:
Copy codeThe Code is as follows:
{# Src/Blogger/BlogBundle/Resources/views/layout.html. twig #}
{% Extends ': base.html. twig' %}
{% Block sidebar %}
Sidebar content
{% Endblock %}
The code is very simple. 1. It inherits the first-level template and customizes the sidebar for the blog content. Obviously, we do not want the blog layout to be the same as that of other pages. Similar to the page-content-type.tpl.php template in drupal7, the layout of a particular type of content is customized.
Specific page layout-level 3
This stage involves creating a specific page, so you need to first create a Controller src/Blogger/BlogBundle/Controller/PageController. php
// src/Blogger/BlogBundle/Controller/PageController.phpnamespace Blogger\BlogBundle\Controller;use Symfony\Bundle\FrameworkBundle\Controller\Controller;class PageController extends Controller{public function indexAction(){return $this->render('BloggerBlogBundle:Page:index.html.twig');}}
Create a Twig file: src/Blogger/BlogBundle/Resources/views/Page/index.html. twig
Copy codeThe Code is as follows:
{# Src/Blogger/BlogBundle/Resources/views/Page/index.html. twig #}
{% Extends 'bloggerblogbundle: layout.html. twig '%}
{% Block body %}
Blog homepage
{% Endblock %}
Create a route and direct the homepage to the page we just created: src/Blogger/BlogBundle/Resources/config/routing. yml
Copy codeThe Code is as follows:
# Src/Blogger/BlogBundle/Resources/config/routing. yml
BloggerBlogBundle_homepage:
Pattern :/
Defaults: {_ controller: BloggerBlogBundle: Page: index}
Requirements:
_ Method: GET
Visit http: // symfony/app_dev.php again to view the simple homepage.
4. Create another about page
Route: Add src/Blogger/BlogBundle/Resources/config/routing. yml
Copy codeThe Code is as follows:
# Src/Blogger/BlogBundle/Resources/config/routing. yml
BloggerBlogBundle_about:
Pattern:/about
Defaults: {_ controller: BloggerBlogBundle: Page: about}
Requirements:
_ Method: GET
When you access the about page in get mode, the page controller about action in the BloggerBlogBundle namespace is executed.
Controller: add the about action to the page Controller in src/Blogger/BlogBundle/Controller/PageController. php.
Copy codeThe Code is as follows:
// Src/Blogger/BlogBundle/Controller/PageController. php
//..
Public function aboutAction ()
{
Return $ this-> render ('bloggerblogbundle: Page: about.html. twig ');
}
//..
Template: Create src/Blogger/BlogBundle/Resources/views/Page/about.html. twig and add relevant Page files
Copy codeThe Code is as follows:
{# Src/Blogger/BlogBundle/Resources/views/Page/about.html. twig #}
{% Extends 'bloggerblogbundle: layout.html. twig '%}
{% Block body %}
About page
{% Endblock %}
The following three simple steps are added: http: // symfony/app_dev.php/about.
I hope this article will help you design PHP programs based on the Symfony framework.
Articles you may be interested in:
- Symfony2 database query method using Doctrine instance Summary
- Summary of how Symfony2 can obtain data from the database
- Symfony2 create page instance details
- Session and cookie usage in Symfony2
- Symfony2 framework learning notes
- Symfony2 Study Notes plugin format Analysis
- System Route details for Symfony2 Study Notes
- A detailed explanation of the controller usage of Symfony2 learning notes
- Template usage of Symfony2 learning notes
- Symfony2 development-controller usage instance analysis
- How to install a third-party Bundles instance in Symfony2
- How to use a third-party library Upload to create an image Upload instance in Symfony2
- Symfony2 joint query Implementation Method