Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Symfony2 creates pages

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces Symfony2 how to create a page, the article introduces in great detail, has a certain reference value, interested friends must read it!

The details are as follows:

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

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

2. Create a controller: the controller is a PHP function that accepts incoming requests and converts them into Response objects for Symfony2.

We like this simple implementation because it fits the way Web works. Every Web interaction starts with an HTTP request, and the task of the application is to simply interpret the request and return the corresponding HTTP response. Symfony2 follows this principle and provides you with the tools to keep it well organized as the user and complexity of your application grows.

"Hello Symfony2" page

Let's start with the classic "hello,world" program. When we are finished, users can get a greeting by visiting the following URL:

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

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

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

Create Bundle

Before you begin, you need to create a Bundle. In Symfony2, Bundle is the equivalent of a plug-in, and all the code in your application needs to be placed in Bundle. A Bundle is just a directory (with the namespace of PHP), all of which are related to a particular function (see the Bundle system). Run the following command to create an AcmeStudyBundle (the game created 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 the autoloading section):

$loader- > registerNamespaces (array ('Acme' = > _ _ DIR__.'/../src', / /...))

Finally, initialize the Bundle 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 rout

By default, the routing configuration file for Symfony2 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.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 the user calls for the "/" (home page) resource, and more interestingly, the last part, which imports other routing profiles located in AcmeStudyBundle.

# src/Acme/StudyBundle/Resources/config/routing.ymlhello: pattern: / hello/ {name} defaults: {_ controller: AcmeStudyBundle:Hello:index}

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

Routing systems have many amazing functions in creating powerful and flexible URL structures for applications. For more information, see "system routing details of Symfony2 Learning Notes".

Create a controller

When a URI such as / hello/Ryan is 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 the process of creating a page is to create this controller

In fact, the controller is nothing more than a PHP function created by you and executed through Symfony2, and this custom application code uses request information to build and prepare the required resources. Except for 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.names);}}

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

Congratulations, just after creating a routing and controller, you have got a full-featured page! If there is nothing wrong with your settings, your application can say hello to you:

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

An optional but frequently 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.

Create a template

Templates allow you to put all the presentations (such as HTML code) into a single file and reuse different blocks 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 shortcuts to common tasks.

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

Note that there are two examples of different rendering templates, and by default, Symfony2 supports two ways of rendering templates: the traditional PHP template and the simple and powerful Twig template. You can choose to use either of them, or you can mix them in the same project, which is no problem.

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, 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 go line by line:

Line 2: extends defines a parent template that explicitly defines a layout file to be replaced

Line 4: block indicates that the contents will replace the block named body, which, as we know, will be responsible for the rendering of the block named body in layout.html.twig.

The parent template:: layout.html.twig omits its bundle name and controller name (so replace it with two colons::), which means that the template is outside the bundle and 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 with the chunk named body that we defined in the index.html.twig template. A block named title is also defined here, or we can choose to define it in the index.html.twig template. Since we do not define the title block in the subtemplate, it still uses the default value of "Hello Application".

Templates are very powerful in rendering and organizing page content, and it can be something that HTML markup language, CSS code, or controller might need to return. A template engine is just a means to an end. The goal of each controller is to return a Response object. The template is powerful, but it is optional. It is just a tool for creating content for Response objects.

Directory structure

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

Although Symfony2's directory structure is quite flexible, by default, Symfony2 still has the same recommended basic directory structure:

App/: this directory contains the application configuration

Src/: the PHP code for all projects is stored in this directory

Vendor/: place all vendor library files in accordance with the convention

Web/: this is the web root directory, including some files that are accessible to the public.

WEB directory

The web root directory is the home directory for all static, public files, including images, stylesheets, and javascript files, where the front controller is located.

/ / 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-end controller (app.php in this case) is actually a PHP file that is executed when using the Symfony2 application. Its function is to use the kernel class AppKernel to let the application bootstrap.

Using a front-end controller means having 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 routing configuration. If you use Apache's rewrite rule, you can enforce it without specifying app.php:

Http://localhost/hello/Ryan

Although the front-end controller is essential when processing requests, you rarely modify it or even think about it, and we only briefly mention it in the environment chapter.

Application (app) directory

As you can see in the front-end controller, the AppKernel class is the main entry for the entire application, it is responsible for all the configuration, and it is stored in the app/ directory.

This class must implement three methods that Symfony2 needs to make known to 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 main configuration resource file of the boot application (see the application configuration section)

3. RegisterRootDir (): returns 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), you will also use the app/cache/ directory as the application cache directory, the app/logs/ directory as the log directory, and the app/Resources/ directory as the application-level resource directory. You will learn more about these directories in the following chapters.

Automatic loading

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

Because of the 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 files that contain what you need.

$loader- > registerNamespaces (array ('Acme' = > _ _ DIR__.'/../src', / /...))

In this configuration, Symfony2 will look for all the classes of the Acme namespace (the imaginary company's namespace) under the src/ directory. In order 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 autoloader to look for different PHP namespaces in different directories and can also be customized if necessary. For more information about the autoloader, see how to automatically load classes.

Source (src) directory

In short, the src/ directory includes all the PHP code that runs in the application. In fact, when developing, most of the work is done in this directory. By default, the src/ directory is empty, and when you start developing, you will begin to populate the directory where bundle is located, which contains the code for your application.

But what on earth is bundle?

Bundle system

Bundle is similar to plug-ins in other software, but better than them. 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 kind of citizen, which makes it very flexible to use the pre-built feature pack of third-party Bundle or to publish your own Bundle. It also makes it easy for you to select the features your application needs and optimize them in your own way.

Bundle is simply a set of structured files used to implement a single function in a directory. 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. Every Bundle contains all aspects of a function, and each function must be implemented in Bundle.

The application consists of the Bundle 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\ new JMS\ new JMS () / / register your bundles new Acme\ StudyBundle\ AcmeStudyBundle (),) If (in_array ($this- > getEnvironment (), array ('dev',' test') {$bundles [] = new Symfony\ Bundle\ WebProfilerBundle\ WebProfilerBundle ();} return $bundles;}

Through the registerBundles () method, you have full control of all the Bundles of the application (including the core Bundle of Symfony2)

No matter where Bundle is, it can be loaded automatically by Symfony2. For example, if AcmeStudyBundle is placed in the src/Acme directory, make sure that the namespace of Acme is added to the app/autoload.php file and mapped to the src/ directory so that it can be loaded automatically 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 called 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 only part of what we need to create a new Bundle. Although empty, this class is powerful enough to customize the behavior of Bundle.

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.

Equally convenient is that 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 will 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 Bundle is simple and flexible. By default, the Bundle system follows a set of conventions that maintain code consistency across all Bundle of Symfony2. Let's look at AcmeStudyoverBundle, because it contains most of the elements of Bundle:

1. Controller/ directory: the controller that contains the Bundle (e.g. HelloController.php)

2. Resources/config/ directory: configuration directory, including routing configuration (e.g. routing.yml)

3. Resources/views/ directory: templates organized by controller name (e.g. Hello/index.html.twig)

4. Resources/public/ directory: contains web resources (pictures, style sheets, etc.) and is copied or softly linked to the web/ directory of the project

5. Tests/ directory: all the tests that store the Bundle.

Depending on the functionality implemented by Bundle, it can be small or large, and it contains only the files you need.

In this book, you will also learn how to persist objects to a database, create and validate forms, translate your applications, write tests, and so on, all of which have their own place and role in Bundle.

Application configuration

An application consists of a set of Bundle that represents all the functions and characteristics of the application. Each Bundle can be customized through a configuration file written by YAML, XML, or PHP. By default, the main configuration file is placed in the app/config/ directory and is named config.yml, config.xml, or config.php, depending on the format you use:

# 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 will show you how to accurately select the file / format to boot in the next section of the environment.

Each top-level entry, such as framework or twig, is configured as a specific Bundle. For example, framework is configured as the core FrameworkBundle of Symfony2 and includes the configuration of routing, templates, and other core systems.

Now don't worry about the specific configuration options in each section of the configuration file, the default values of the configuration file are reasonable. When you browse the various parts of Symfony2, you will learn the specific configuration options for each part.

Configuration format

Throughout the chapter, all configuration examples are shown in three formats (YAML, XML, and PHP). Each of them has its own advantages and disadvantages, and here are descriptions of the three formats:

1. YAML: simple, clean and easy to read

2. XML: sometimes more powerful than YAML and supporting the automatic completion of IDE

3. PHP: very powerful, but less readable than the standard configuration format

Environment

Applications can run in different environments. Different environments share the same PHP code (distinguished by the front-end controller), but have completely different configurations. The development environment logs warnings and errors, while the production environment records only errors. Some files are refactored after each request in the development environment, but are cached in the production environment. All environments live in the same mechanism.

While it is easy to create a new environment, Symfony2 projects usually start with three environments (development, testing, and production). By changing the front controller in your browser, you can easily switch applications in different environments. To switch the application 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 performs 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 is clearly configured to use a production environment:

$kernel = new AppCache (new AppKernel ('prod', false))

You can create a new front-end controller for a new environment by copying the file and changing 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 at the same time. When changing the view in a production environment, you need to clear these cache files so that they can be refactored:

Rm-rf app/cache/*

The test environment is used when automated testing, which is not directly accessible from the browser. See the testing section for more details.

Environment configuration

The AppKernel class is responsible for loading the configuration file of your choice:

/ / app/AppKernel.phppublic function registerContainerConfiguration (LoaderInterface $loader) {$loader- > load (_ _ DIR__.'/config/config_'.$this- > getEnvironment (). '.yml');}

We already know that the .yml extension can be converted to .xml or .php, as long as you prefer to use XML or PHP to write the configuration. Note that each environment can also load its own configuration file. The following is the configuration file 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, first guides the main configuration file (config.yml), and the rest of the file adjusts the default configuration for growing logs and other settings that benefit the development environment.

Follow the same model in both production and test environments: each environment imports basic configuration files and then modifies their configuration values to meet the needs of a particular environment.

The above is all the content of the article "how to create a page for Symfony2". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report