Symfony2 creating a Page instance, symfony2 example _php tutorial

Source: Internet
Author: User
Tags autoload autoloader naming convention php template

Symfony2 Create a page instance in detail, symfony2 instance detailed


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

Creating a page in Symfony2 requires only two steps:

1. Create a route : The 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 a controller : The controller is a PHP function that accepts incoming requests and converts them into Symfony2 response objects.

We like this simple implementation because it fits the way the Web works. Each web interaction begins with an HTTP request, and the task of the application 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 the application remains well organized as it grows.

"Hello Symfony2" page

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

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

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

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

Create bundles

Before you start, you need to create a bundle. In Symfony2, bundles are the equivalent of plugins, and all the code in your application needs to be placed in bundles. Bundles are just a directory (with PHP namespaces), and the content is related to a particular feature (see Bundle System). Run the following command to create the Acmestudybundle (the game you built in this chapter).

PHP app/console acme/studybundle[/]

Next, the following statement is added to the app/autoloader.php file to ensure that the Acme namespace is booted (see Auto-load Chapters):

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

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

App/appkernel.phppublic 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.

Create a route

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

# App/config/routing.ymlhomepage:  pattern:/  defaults: {_controller:frameworkbundle:default:index}hello:  resource: "@AcmeStudyBundle/resources/config/routing.yml"

The first few lines of the routing profile define the code that is called by the user Request "/" (home) resource, and, more interestingly, the last part, which imports other routing profiles in Acmestudybundle.

# Src/acme/studybundle/resources/config/routing.ymlhello:  pattern:/hello/{name}  defaults: {_controller: AcmeStudyBundle:Hello:index}

The route consists of two basic parts, pattern (schema) that determines which URI matches this route, and the defaults array specifies the controller to run. The placeholder {name} in pattern is a wildcard that represents a URI that matches the route, such as/hello/ryan,/hello/fabien, or other similar URIs. 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 an application's powerful, flexible URL structure, see the Symfony2 Learning Notes system Routing details

Create a Controller

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

In fact, the controller is simply a PHP function that you create and execute via Symfony2, which 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.phpnamespace Acme\studybundle\controller;use Symfony\Component \httpfoundation\response;class hellocontroller{public  function indexaction ($name)  {    return new Response (' Hello '. $name. '! ');}  }

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

Congratulations, just after you've created a route and controller, you've got a full-featured page! If your setup is not a problem, your app will be able to greet you with:

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

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

When creating a page, the controller is the main entrance and the key section, and more information can be found in the controller section.

Create a template

Templates allow you to put all your impressions (such as HTML code) into a single file and reuse different chunks of the page layout. The following code uses a template to replace the HTML code in the controller.

Src/acme/studybundle/controller/hellocontroller.phpnamespace 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 template    //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 shortcut methods for 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. You can choose to use one of these, or you can mix them in the same project, which is no problem.

The controller renders a AcmeStudyBundle:Hello:index.html.twig template that uses the following naming conventions:

Bundle Name: Controller name: template name

In this example, Acmestudybundle is the bundle name, Hello is the controller, and 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's line up to:
Line 2nd: Extends defines a parent template that explicitly defines a layout file that will be replaced;
Line 4th: Block indicates that the content will replace the block named body, as we know it will be responsible for rendering 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 with two colons:: instead), which means that the template is outside the bundle, in the app directory.

{# App/resources/views/layout.html.twig #}      
 
      {% block title%} Hello application{% endblock%}        {% block body%} {% Endblock%}  

The basic template file defines the HTML layout and renders it with a chunk named body that we define in the Index.html.twig template. A chunk named title is also defined here, and we can also choose to define it in the Index.html.twig template. Since we did not define the title chunk in the child template, it still uses the default value "Hello Application".

Templates are very powerful in rendering and organizing page content, which can be HTML identity language, CSS code, or something the controller might need to return. The template engine is just the means to reach the goal. The goal of each controller is to return a response object, which, while powerful, is optional and is simply 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 have begun 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 directory structure of Symfony2 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 project PHP code is saved in this directory;
vendor/: Place all vendor's library files according to the agreement;
web/: This is the Web root directory, including some files that the public can access.

Web Directory

The Web root is the home directory of all static, public files, including images, style sheets, and JavaScript files, where the front controller resides.

Web/app.phprequire_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 controller (here is app.php) is actually a PHP file that executes when using the Symfony2 application. Its function is to use the 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 is as follows:

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

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

Http://localhost/hello/Ryan

While the front-end controller is essential for processing requests, you rarely modify or even think about it, and we just mention it briefly 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, which is responsible for all configurations and is stored in the app/directory.

This class must implement three methods that Symfony2 needs 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 (): The master configuration resource file that directs the application (see the Application configuration section);
3, Registerrootdir (): Return to the app root directory (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 application's cache directory, use the app/logs/directory as the log directory, use the app The/resources/directory is an application-level resource directory. You will learn more about these directories 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 there is an autoloader, 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 file that contains the one you want.

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

In this configuration, Symfony2 will look for all classes in the Acme namespace (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 Configure the autoloader to find different PHP namespaces in different directories, or to customize them if necessary. For more information about the autoloader, 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 the time of development. By default, the src/directory is empty, and when you start developing it, you will start populating the directory where the bundle is located, which contains the code for your application.
But what exactly is the bundle?

Bundle system

Bundles are similar to plugins in other software, but better than them. The key difference is that everything is bundles in Symfony2, including the core functionality of the framework and the code you write for your application. In Symfony2, bundles are a class of citizens, which makes it very flexible to use a third-party bundle's pre-built feature pack or to publish your own bundles. It also allows you to easily select the features your application needs and optimize them in your own way.

Bundles are simply a structured set of files that can be used to implement a single function in a directory. You can create Blogbundle, Forumbundle, or user-managed bundles (many of them already exist in the form of open source bundles). 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, each of which must be implemented in the bundle.

An application consists of bundles defined in the Registerbundles () method in the Appkernel class:

App/appkernel.phppublic 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 of all bundles of the application (including the core bundle of Symfony2)

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

Create bundles

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.phpnamespace Acme\testbundle;use Symfony\component\httpkernel\bundle\bundle ; class Acmetestbundle extends bundle{}

Acmetestbundle follows the bundle naming convention

This empty class is just part of the new bundle we need to create. Although empty, this class is powerful enough to be used to customize the behavior of bundles.

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

App/appkernel.phppublic function Registerbundles () {  $bundles = array (    //...    Register your bundles    new Acme\testbundle\acmetestbundle (),  );  // ...  return $bundles;}

Although it can't do anything yet, Acmetestbundle is now ready to use it.

Equally handy, Symfony also provides the command line interface to generate the basic framework of bundles

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

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

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

Directory Structure of Bundles

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

1. controller/Directory: The controller containing the bundle (for example: hellocontroller.php);
2, resources/config/directory: Configuration directory, including routing configuration (such as: ROUTING.YML);
3, resources/views/directory: through the Controller name Organization template (such as: Hello/index.html.twig);
4, resources/public/directory: Contains Web resources (pictures, style sheets, etc.), and is copied or soft links to the project's web/directory;
5. tests/Directory: All tests that store the bundle.

Depending on the functionality implemented by the bundle, it can be large and 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 have their place and role in the bundle.

Application Configuration

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

# App/config/config.ymlframework:  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 configurationtwig:  debug:      %kernel.debug%  strict_variables:%kernel.debug%

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

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

Now don't worry about the specific configuration options in the sections in the configuration file, the profile defaults are reasonable. When you browse through the sections of Symfony2, you will learn the specific configuration options for each section.

Configuration format

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

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

Environment

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

Although it is easy to create a new environment, SYMFONY2 projects typically start with three environments (development, testing, and production). By changing the front-end controller in your browser, you can easily allow your application to switch between different environments. To switch applications to the development environment, you only need to access the application by developing a 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 call 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 change the prod to a different value.

Because the production environment is optimized for speed, the configuration, routing, and Twig templates are compiled into pure PHP classes and cached at the same time. When you change the view in a production environment, you need to clear these cache files so that they can be refactored:

RM-RF app/cache/*

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

Environment configuration

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

App/appkernel.phppublic function registercontainerconfiguration (loaderinterface $loader) {  $loader->load ( __dir__. ' /config/config_ '. $this->getenvironment (). Yml ');}

We already know. The. yml extension can be converted to. xml or. php, as long as you prefer to write the configuration using XML or PHP. Note 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.ymlimports:  -{resource:config.yml}framework:  Router:  {resource: "% Kernel.root_dir%/config/routing_dev.yml "}  Profiler: {only_exceptions:false}web_profiler:  toolbar:true  intercept_redirects:truezend:  logger:    priority:debug    path:   %kernel.logs_dir%/% Kernel.environment%.log

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

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

Summary

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

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/(config), src/(your bundle), and vendor/(third-party code);
3, Symfony2 each function (including SYMFONY2 framework Core) is organized into a bundle,bundle is the function of the structure of the file set;
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 (e.g. app.php or app_dev.php) and configuration files.

It is hoped that this article is helpful to the PHP program design based on Symfony framework.

Articles you may be interested in:

    • Implementation method of Symfony2 Federated query
    • Analysis of date usage in twig of symfony2.4
    • Summary of Symfony2 's session and cookie usage
    • Symfony2 a summary of how to achieve data acquisition from a database
    • Symfony2 Framework Learning Notes Form usage
    • Analysis of plugin format of Symfony2 learning notes
    • Symfony2 Study Notes System routing
    • Symfony2 study notes of the controller usage detailed
    • Symfony2 Study Notes Template usage detailed
    • Symfony2 installing a third-party bundles instance
    • An example analysis of Symfony2 function usage

http://www.bkjia.com/PHPjc/1111903.html www.bkjia.com true http://www.bkjia.com/PHPjc/1111903.html techarticle Symfony2 Create a page instance in detail, symfony2 example of this article describes the Symfony2 method of creating a page. Share to everyone for your reference, as follows: Create a page in Symfony2 ...

  • Related Article

    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.