Symfony2 Create a page instance detailed _php instance

Source: Internet
Author: User
Tags autoload http request naming convention

The example in this article describes how Symfony2 creates a page. Share to everyone for your reference, specific as follows:

It takes only two steps to create a page in Symfony2:

1. Create Route : Route defines the URI of your page (such as/about) and specifies the controller (PHP function) to execute. When the incoming request URL matches the route, Symfony2 executes the specified controller;

2. Create controller : Controller is a PHP function that accepts incoming requests and converts them to Symfony2 response objects.

We like this simple implementation because it conforms to how the Web works. Each web interaction starts with an HTTP request, and the application's task is simply to interpret the request and return the corresponding HTTP response. Symfony2 follows this principle and provides you with the tools to ensure that the user and complexity of your application grow and remain well organized.

"Hello Symfony2" page

Let's start with the classic "Hello,world" program, and when we're done, users can get a greeting by accessing the following URLs:

Http://localhost/app_dev.php/hello/Symfony

In fact, you can change the symfony to another name to greet, to create the page, we simply go through two steps:

This tutorial already assumes that you have downloaded the SYMFONY2 and configured the Web server. The above URL assumes localhost points to your new Symfony2 project. Installation details see installing Symfony2.

Create bundle

Before you start, you need to create a bundle. In Symfony2, bundle is the equivalent of Plug-ins, and all the code in your application needs to be placed in bundle. Bundle is just a directory (with a PHP namespace) and the contents are related to a particular function (see bundle system). Run the following command to create the Acmestudybundle (the game that is built in this chapter).

PHP app/console acme/studybundle[/]

Next, add the following statement to the app/autoloader.php file to ensure that the Acme namespace is booted (see automatically loading chapters):

$loader->registernamespaces Array (
  ' Acme ' => __dir__. ') /.. /src ',
  //...)
;

Finally, the bundle is initialized in the Registerbundles () method of the app/appkernel.php file.

app/appkernel.php Public
function Registerbundles ()
{
  $bundles = array (
    //...
    ) New Acme\studybundle\acmestudybundle (),
  );
  // ...
  return $bundles;
}

Now that you have set up your bundle, you can build your application in your bundle.

Creating routes

By default, the Symfony2 routing configuration file is placed in the APP/CONFIG/ROUTING.YML directory. All configuration files in Symfony2 can also be written in PHP or XML format.

# app/config/routing.yml
homepage: pattern
  :/
  defaults: {_controller:frameworkbundle:default:index}
Hello:
  resource: "@AcmeStudyBundle/resources/config/routing.yml"

The first few lines of the routing configuration file define the code that the user requests "/" (home) resource calls, and more interestingly, the last part, which imports other routing profiles located in Acmestudybundle.

# src/acme/studybundle/resources/config/routing.yml
Hello: Pattern
  :/hello/{name}
  Defaults: {_ Controller:AcmeStudyBundle:Hello:index}

Routing consists of two basic parts, pattern (mode) determines which URI matches this route, and the defaults array specifies the controller to run. The placeholder {name} in pattern is a wildcard character that represents a/hello/ryan,/hello/fabien, or other similar URI that matches the route. The {name} placeholder parameter is also sent to the controller so that we can use its value to greet the user.

The routing system has many amazing features in creating powerful, flexible URL structures for applications, please see "Symfony2 Learning Notes System Routing Details"

Creating a Controller

When a URI such as/hello/ryan is processed by an application, the Hello route is matched and the AcmeStudyBundle:Hello:index controller is executed through the SYMFONY2 framework. The second step in creating the page process is to create this controller

In fact, the controller is simply a PHP function that you create and execute through Symfony2, and the custom application code uses the request information to build and prepare the required resources. In addition to some advanced cases, the final output of the controller is the same: a response object.

src/acme/studybundle/controller/hellocontroller.php
namespace Acme\studybundle\controller;
Use Symfony\component\httpfoundation\response;
Class Hellocontroller
{public
  function indexaction ($name)
  {return
    new Response ('  
 

The controller is simple, it creates a new response object whose first argument is the response content it returns (in this case, a small HTML page).

Congratulations, just after you've created a Routing and controller, you've got a full-featured page! If your settings are OK, your application will be able to greet you:

Http://localhost/app_dev.php/hello/Ryan

An optional but often-used step is to create a template.

The controller is the main entry and key part when creating the page, and more information can be found in the controller section.

Creating templates

Templates allow you to put all the presentations (such as HTML code) into a single file, and reuse different chunks of the page layout. The following code is used to replace the HTML code in the controller with a template.

src/acme/studybundle/controller/hellocontroller.php
namespace Acme\studybundle\controller;
Use Symfony\bundle\frameworkbundle\controller\controller;
Class Hellocontroller extends Controller
{public
  function indexaction ($name)
  {return
    $this-> Render (' AcmeStudyBundle:Hello:index.html.twig ', Array (' name ' => $name));
    Render PHP templates
    //return $this->render (' AcmeStudyBundle:Hello:index.html.php ', Array (' name ' => $name)
  }
}

In order to use the render () method, you must inherit the controller class, which adds a quick way to some common tasks.

The render () method creates a response object that is populated with specific content and rendered through a template. As with other controllers, you end up with a response object.

Note that there are two examples of different rendering templates, by default, Symfony2 supports two ways to render templates: traditional PHP templates and simple, powerful twig templates. It's not a problem if you choose to use either of these or you can mix them in the same project.

The controller renders the AcmeStudyBundle:Hello:index.html.twig template, which uses the following naming convention:

Bundle Name: Controller name: template name

In this case, Acmestudybundle is the bundle name, Hello is the controller, Index.html.twig is the template name.

{# Src/acme/studybundle/resources/views/hello/index.html.twig #}
{% extends ':: Layout.html.twig '%}
{% block body%}
  Hello {{Name}}!
{% Endblock%}

Let us come in line:
Line 2nd: Extends defines a parent template that explicitly defines a layout file that will be replaced;
Line 4th: Block means that the contents will replace block named body, as we know it will be responsible for the rendering of the block named body in Layout.html.twig in the final rendering.
Parent Template:: Layout.html.twig omits its bundle name and controller name (so use two colons:: instead), which means that the template is outside of bundle, in the app directory.

{# App/resources/views/layout.html.twig #}
<! DOCTYPE html>
 
 

The base template file defines the HTML layout and renders it in the block named body that we defined in the Index.html.twig template. This also defines a block named title, which we can also choose to define in the Index.html.twig template. Since we did not define the title block in the child template, it still uses the default value "Hello Application".

Templates are powerful in rendering and organizing page content, which can be HTML markup Language, CSS code, or something the controller might need to return. The template engine is just the means to achieve the goal. The goal of each controller is to return a response object, which, while powerful, is optional and is just a tool for creating content for response objects.

Directory structure

After a few paragraphs of learning, you have understood the steps to create and render pages in Symfony2, and you are beginning to understand the organization and structure of Symfony2, and at the end of this chapter you will learn where to find and place different types of files and why.

Although the SYMFONY2 directory structure is quite flexible, in the default state, Symfony2 still has the same, recommended basic directory structure:

app/: This directory contains the application configuration;
src/: All the project's PHP code is saved in the directory;
vendor/: To place all suppliers ' library documents according to the contract;
web/: This is the Web root directory, including some files that the public can access.

Web Directory

The Web root is a home directory of all static, public files, including images, style sheets, and JavaScript files, and this is where the front-end controllers are located.

web/app.php
require_once __dir__. ' /.. /app/bootstrap.php ';
Require_once __dir__. ' /.. /app/appkernel.php ';
Use Symfony\component\httpfoundation\request;
$kernel = new Appkernel (' prod ', false);
$kernel->handle (Request::createfromglobals ())->send ();

The front-end controller (here is app.php) is actually a PHP file that is executed when using the Symfony2 application. Its function is to use kernel class Appkernel, let the application bootstrap.
Using a front-end controller means a more flexible URL than using a traditional pure PHP program, and when using a front-end controller, the URL format looks like this:

Http://localhost/app.php/hello/Ryan

The front-end controller app.php is executed, and the URI (/hello/ryan) is routed through the routing configuration. If you use the Apache rewrite rule, you can enforce it without specifying a app.php:

Http://localhost/hello/Ryan

While the front-end controller is essential for processing requests, you rarely change or even think about it, and we simply mention it in the environment chapter.

Application (APP) directory

As you can see in the front-end controller, the Appkernel class is the main portal for the entire application, and it is responsible for all configurations, which are stored in the app/directory.

This class must implement three methods that Symfony2 need to be understood by the application. You don't even have to worry about these methods in the first place, because Symfony2 will intelligently populate them for you:

1, Registerbundles (): Returns all bundle arrays that need to be run in the application (see bundle System);
2, Registercontainerconfiguration (): Boot the application's main configuration resource file (see application configuration section);
3, Registerrootdir (): Return to App Root (default is app/)

In daily development, you will often use the app/directory, you will modify the configuration and routing files in the app/config/directory (see application configuration), also use the app/cache/directory as the cache directory for the application, using the app/logs/directory as a log directory, using the app The/resources/directory is the application-level resource directory. You will learn more about these catalogues in the following sections.

Auto Load

When the application is bootstrap, it will contain a special file: app/autoload.php. This file is responsible for automatically loading all files in the src/and vender/directories.

Because of the automatic loader, you never have to worry about using include or require statements. Symfony2 uses the namespace of the class to determine its location and automatically loads the class files that contain your needs.

$loader->registernamespaces Array (
  ' Acme ' => __dir__. ') /.. /src ',
  //...)
;

In this configuration, Symfony2 will look for all classes in the Acme namespace (the imaginary Company's namespace) under the src/directory. In order to be able to load automatically, the Class name file and path must follow the same pattern:

Class Name:
Acme\studybundle\controller\hellocontroller
Path:
src/acme/studybundle/controller/hellocontroller.php

App/autoload.php configures the Autochanger to look for different PHP namespaces in different directories, or it can be customized if necessary. For more information about automatic loaders, see How to load classes automatically.

Source (SRC) directory

In short, the src/directory includes all the PHP code that runs in the application. In fact, most of the work is done in this directory at development time. By default, the src/directory is empty, and when you start developing, you'll start populating the directory where bundle resides, which contains the code for your application.
But what exactly is bundle?

Bundle system

Bundle are similar to plug-ins in other software, but they are better than they are. The key difference is that everything is bundle in Symfony2, including the core functionality of the framework and the code you write for your application. In Symfony2, bundle is a class of citizen, which makes it very flexible to use a pre-built feature package from a Third-party bundle or to publish your own bundle. It also makes it easy for you to select the features that your application requires and optimize them in your own way.

Bundle is simply a set of structured files that are used in a directory to achieve a single function. You can create Blogbundle, Forumbundle, or user-managed bundle (many already exist in the form of open source bundle). Each directory contains functionality-related content, such as php files, templates, style sheets, javascripts, tests, and so on. Each bundle contains all aspects of a function, and each feature must be implemented in bundle.

The application consists of the bundle defined in the Registerbundles () method in the Appkernel class:

app/appkernel.php Public
function Registerbundles ()
{
  $bundles = array (
    new symfony\bundle\ Frameworkbundle\frameworkbundle (),
    new Symfony\bundle\securitybundle\securitybundle (),
    new Symfony\ Bundle\twigbundle\twigbundle (),
    new Symfony\bundle\monologbundle\monologbundle (),
    new symfony\bundle\ Swiftmailerbundle\swiftmailerbundle (),
    new Symfony\bundle\doctrinebundle\doctrinebundle (),
    new Symfony\ Bundle\asseticbundle\asseticbundle (),
    new Sensio\bundle\frameworkextrabundle\sensioframeworkextrabundle (),
    new Jms\securityextrabundle\jmssecurityextrabundle (),
    //Register your bundles
    new Acme\studybundle \acmestudybundle (),
  );
  if (In_array ($this->getenvironment (), Array (' Dev ', ' test ')) {
    $bundles [] = new symfony\bundle\ Webprofilerbundle\webprofilerbundle ();
  }
  return $bundles;
}

With the Registerbundles () method, you have full control over all bundles of the application (including the Symfony2 core bundle)

No matter where the bundle is, it can be automatically loaded by Symfony2. For example, if Acmestudybundle is placed in the SRC/ACME directory, make sure that Acme's namespace is added to the app/autoload.php file and mapped to the src/directory so that it can be automatically loaded by Symfony2.

Create bundle

To show you how simple the bundle system is, let's create a new bundle called Acmetestbundle and activate it.

First, create a src/acme/testbundle/directory and add a new file named acmetestbundle.php:

src/acme/testbundle/acmetestbundle.php
namespace Acme\testbundle;
Use Symfony\component\httpkernel\bundle\bundle;
Class Acmetestbundle extends Bundle
{
}

Acmetestbundle Follow bundle naming convention

This empty class is just part of the new bundle we need to create. Although it is empty, this class is already strong enough and can be used to customize the behavior of bundle.

Now that we have created our bundle, we need to activate it through the Appkernel class:

app/appkernel.php Public
function Registerbundles ()
{
  $bundles = array (
    //...
    ) Register your bundles
    new acme\testbundle\acmetestbundle ()
  ;
  // ...
  return $bundles;
}

Although it can't do anything at the moment, Acmetestbundle is now ready to use.

Equally conveniently, Symfony also provides a command-line interface to generate the basic framework of bundle

PHP app/console init:bundle "Acme\testbundle" src

The generated bundle framework includes a basic controller, templates, and customizable routing resources. Next we'll discuss more Symfony2 command-line tools.

Whenever you create a new bundle or use a third-party bundle, you need to make sure that the bundle is activated in Registerbundles ().

Directory Structure of Bundle

The directory structure of the bundle is simple and flexible. By default, the bundle system follows the set of conventions that maintain code consistency between all bundle Symfony2. Let's look at Acmestudyoverbundle, because it contains most of the elements of bundle:

1, controller/directory: containing the bundle controller (such as: hellocontroller.php);
2, resources/config/directory: Configuration directory, including routing configuration (such as: ROUTING.YML);
3, resources/views/directory: Through the controller name of the organization template (such as: Hello/index.html.twig);
4, resources/public/directory: Contains Web resources (pictures, style sheets, etc.), and is copied or soft link to the project's web/directory;
5, tests/directory: Storage of the bundle of all tests.

According to the bundle implementation of the function, it can be large, it contains only the files you need.

In this book you will also learn how to persist objects to databases, create and validate forms, translate your applications and write tests, and so on, and they all have their place and role in bundle.

Application Configuration

An application consists of a bundle set that represents all the features and features of an application. Each bundle can be defined by a configuration file written in Yaml, XML, or PHP. By default, the primary configuration file is placed in the app/config/directory, named Config.yml, Config.xml, or config.php, depending on the format you are using:

# app/config/config.yml
Framework:
  CharSet:     UTF-8
  Secret:     xxxxxxxxxx
  form:      True
  csrf_protection:true
  Router:     {resource: "%kernel.root_dir%/config/routing.yml"}
  Validation:   {annotations:true}
  templating:   {engines: [' Twig ']} #assets_version: Someversionscheme
  Session:
    default_locale:en
    lifetime:    3600
    Auto_start:   true
# Twig Configuration
twig:
  debug:      %kernel.debug%
  strict_variables:%kernel.debug%

We'll show you how to accurately select the file/format to boot in the next section of the environment.

Each top-level entry, such as a framework or twig, is configured as a specific bundle. For example, the framework is configured as a Symfony2 core frameworkbundle and contains the configuration of routes, templates, and other core systems.

Now don't worry about the specific configuration options in each segment of the configuration file, the profile defaults are reasonable. As you navigate through the parts of Symfony2, you will learn the specific configuration options for each section.

Configuration format

Throughout the chapter, all of the configuration examples are presented in three formats (YAML, XML, and PHP). Each of them has its own pros and cons, and the following are descriptions of three formats:

1, YAML: simple, clean and easy to read
2, XML: Sometimes more powerful than YAML and support the automatic completion of the IDE
3, PHP: very powerful, but compared with the standard configuration of the readability of the poor

Environment

Applications can run in different environments. Different environments share the same PHP code (which is differentiated by the front-end controller), but it has a completely different configuration. The development environment logs warnings and errors, and the production environment logs errors only. In the development environment, some files are refactored after each request, but are cached in the production environment. All environments live in the same mechanism.

While it is easy to create new environments, Symfony2 projects typically start with three environments (development, testing, and production). By changing the front-end controller in your browser, you can easily allow applications to switch in different environments. To switch applications to the development environment, you only need to access the application by developing the front-end controller.

Http://localhost/app_dev.php/hello/Ryan

If you want to see how your application behaves in a production environment, you can invoke the production front-end controller:

Http://localhost/app.php/hello/Ryan

If you open the web/app.php file, you will find that it has been explicitly configured to use the production environment:

$kernel = new AppCache (New Appkernel (' prod ', false));

You can create a new front-end controller for a new environment, just copy the file and modify the prod to other values.

Because the production environment is optimized for speed, configuration, routing, and Twig templates are compiled into pure PHP classes and cached. When you change views in a production environment, you need to clear the cached files so that they refactor:

RM-RF app/cache/*

When you use a test environment for automated testing, it is not directly accessible from the browser. See the test section for more details.

Environment configuration

The Appkernel class is responsible for loading the configuration file you selected:

app/appkernel.php Public
function registercontainerconfiguration (loaderinterface $loader)
{
  $ Loader->load (__dir__. ') /config/config_ '. $this->getenvironment (). Yml ');
}

We already know. yml extensions can be converted to. xml or. php, as long as you prefer to use XML or PHP to write configurations. Note that each environment can also load their own configuration files. The following are the configuration files that are prepared for the production environment.

# app/config/config_dev.yml
Imports:
  -{RESOURCE:CONFIG.YML}
framework:
  Router:  {resource: "% Kernel.root_dir%/config/routing_dev.yml "}
  Profiler: {only_exceptions:false}
Web_profiler:
  toolbar: True
  intercept_redirects:true
Zend:
  logger:
    priority:debug
    path:   %kernel.logs_dir %/%kernel.environment%.log

The Import keyword, like the include statement in PHP format, first boots the master configuration file (Config.yml), and the rest of the file is adjusted for the default configuration for increased logs and other settings that are conducive to the development environment.

The same model is followed in both the production environment and the test environment: Each environment imports basic profiles and then modifies their configuration values to suit the needs of the particular environment.

Summary

Congratulations, you have now understood the fundamentals of Symfony2 and are pleasantly surprised to find it so handy and flexible. Although there are many features, we can keep the following basic points in mind:

1, create a page requires three steps, including routing, Controller and template (optional);
2. Each application should contain four directories: web/(Web resource and front-end controller), app/(configuration), src/(your bundle) and vendor/(third party code);
3, each function of Symfony2 (including the Symfony2 frame core) is organized into a bundle,bundle is a structured file set of the function;
4, each bundle configuration is stored in the App/config directory, you can use YAML, XML and PHP to write;
5. Each environment can be accessed through different front-end controllers (such as: app.php or app_dev.php) and configuration files.

I hope this article will help you with the PHP program design based on Symfony framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.