Symfony2 Learning Note Plug-in format analysis _php instance

Source: Internet
Author: User
Tags configuration settings
This article describes the plug-in format for Symfony2. Share to everyone for your reference, as follows:

A bundle is similar to a plugin in other frameworks, but it behaves better than a plugin. The main difference with other frameworks is that everything in Symfony2 is bundle, including core framework functions and all the application code you write. In Symfony2, bundles are a class citizen. This gives you more flexibility in using content packages developed by other third parties or distributing your own bundles. You can easily choose which content can be applied to your programs that don't need to optimize them according to your ideas.

A bundle is a directory that has a good structure that can store everything from classes to controllers and Web resources.

A bundle is simply a collection of structured file directories that implement a single content.

You can create a blogbundle, a forumbundle or a bundle that implements user management (as if there are already many such open source bundles). Each bundle directory contains everything that is relevant to the implementation, including PHP files, templates, stylesheets, JavaScript files, test content, and any other related things. All aspects of the content to be implemented are saved in a bundle.

An application is made up of all the bundles defined in the Registerbundles () method in the Appkernel class.

App/appkernel.phppublic function Registerbundles () {$bundles = array (new SYMFONY\BUNDLE\FRAMEWORKBUNDLE\FRAMEWORKB Undle (), New Symfony\bundle\securitybundle\securitybundle (), New Symfony\bundle\twigbundle\twigbundle (), New SYMF Ony\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 (),);    if (In_array ($this->getenvironment (), Array (' Dev ', ' test ')) {$bundles [] = new Acme\demobundle\acmedemobundle ();    $bundles [] = new Symfony\bundle\webprofilerbundle\webprofilerbundle ();    $bundles [] = new Sensio\bundle\distributionbundle\sensiodistributionbundle ();  $bundles [] = new Sensio\bundle\generatorbundle\sensiogeneratorbundle (); } return $bundles;}

Here you can use this method to unify control and manage your application composition.

A bundle can be stored in any directory and can be loaded automatically only by configuring the autoloader in the app/autoload.php file.

Create a bundle

A full-featured tool file for creating bundles has been prepared for you in the Symfony2 Standard Edition. You can run it to create all the content of the bundle, and of course you can

Choose to create them manually. Now we create a acmetestbundle and let it work in our application. Note that Acme here is a bogus provider name and you can completely replace it for your own organization or company name.

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

Src/acme/testbundle/acmetestbundle.phpnamespace Acme\testbundle;use Symfony\component\httpkernel\bundle\bundle ; class Acmetestbundle extends bundle{}

Next, to make it available in your application, you need to add it in the Registerbundles () method in 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 now, it's already part of your application.

We can also use Symfony2 to provide us with command-line tools to create:

$ php app/console generate:bundle--namespace=acme/testbundle

If you use the command-line tool above, the created bundle is automatically registered in the Appkernel class.

Directory Structure of Bundles

Take a look at the directory structure of our demo bundle Symfony2:

The directory structure of bundles is simple and flexible, as can be seen from the above:

controller/contains all the controllers files for the bundle, such as hellocontroller.php.
Dependencyinjection/holds a specific dependency injection extension class, which may import service configurations, register compiler transports, or more. This directory is not required.
The resources/config/stores the configuration files, including the routing configuration (for example: ROUTING.YML).
resources/views/all the templates are stored in a folder according to the name of the corresponding controller. Like Hello/index.html.twig.
resources/public/all accessible Web resources (Pictures, stylesheets, and so on) and copy or asynchronously link to the contents of the project web/directory through the assets:install console command.
tests/Save Bundles all the tests

Here are some of the standard rules that SYMFONY2 recommends for bundles:

Bundle Name:

A bundle is also a PHP namespace. namespaces must conform to internal technical standards for PHP5.3 namespaces and class names. Start with the provider name, followed by the category segment (which can be omitted), and finally the abbreviated name of the namespace, and the name must be given a bundle as a suffix. A namespace becomes a bundle that only requires you to add a bundle class within that namespace.

Name of bundle class:

Only numbers, letters and underscores are applicable
Use hump-style naming
Use a descriptive concise name (no more than two words)
Prefix with vendor name (optional categorical namespace)

Add bundle as name suffix

Like what:

Namespace = Bundle class name

Acme\bundle\blogbundle = Acmeblogbundleacme\bundle\social\blogbundle =>acmesocialblogbundleacme\blogbundle = Acmeblogbundle

The GetName () method when defining the bundle class should return the class name.

Each bundle has an alias, which is the bundle name for the abbreviated version of lowercase characters and is split with underscores. For example, Acme_hello bundle formerly known as Acmehellobundle, Acme_social_blog is an example of acme\social\blogbundle.

Aliases must be unique within a bundle.

Directory structure of Bundles: Hellobundle's underlying directory structure

  xxx/... hellobundle/    hellobundle.php    controller/    resources/      meta/        LICENSE      config/      doc/        index.rst      translations/      views/      public/    tests/

Above the xxx/... The namespace that is mapped to the bundle. The following files are required:

hellobundle.php;

Resources/meta/license: Full-text license code;
The root directory file for the resources/doc/index.rst:bundle description.

The depth of the subfolder used for the class should be kept to a minimum (level 2 is the limit). If more levels can be defined as non-static, it is seldom used. The directory of the bundle is read-only. If you need to modify temporary files, save them to the main application's cache/or log/directory.

Classes and files to emphasize

Type VS Directory

Commands VS command/
Controllers VS controller/
Service Container Extensions vs/dependencyinjection/
Event Listeners VS eventlistener/
Configuration VS Resources/config
Web Resources VS Resources/public
Translation Files VS resources/translations/
Templates VS Resources/views
Unit and functional Test VS tests/

Class:

The bundle's directory structure is used as a namespace-level. For example, the Hellocontroller class is saved in the bundle/hellobundle/controller/hellocontroller.php file.

So the fully qualified name of the class is Bundle\hellobundle\controller\hellocontroller. Some classes are considered to be decorative, and should be as short as possible, such as Commands,helpers, Listeners and controllers, and so on, will generally be used as suffixes.

Classes related to the event dispatcher should be identified with the suffix listener.

The exception class should be saved in a exception child namespace.

About providers

A bundle should not be embedded in a third-party PHP class library, it should rely on the SYMFONY2 standard to automatically load them.

A bundle should not be embedded in any class library written by a third-party javascript,css or other language.

About testing

A bundle should have a test unit that uses PHPUnit and store it in the tests/directory.

Testing should follow these guidelines:

The test suite must be able to be executed from a simple application with a simple phpunit command.

Functional testing should only be used to test the reply output and some monitoring information.

The test code overrides the base code that should be at least above 95%.

A test suite can contain no alltests.php scripts, but must rely on external phpunit.xml.dist files.

Document description

All classes must have phpdoc.

Controllers

In the best case, the controller should be in a bundle that can be deployed somewhere else, then it cannot inherit the controller base class. Instead, the inherited controller is replaced by implementing the Containerawareinterface interface or inheriting the Containeraware.

Routing

If bundles provide routing, they must prefix the alias of the bundle, such as a acmeblogbundle instance, and all the route names must start with Acme_blog_.

Templates

If the bundle provides a template, it must use twig. Bundles do not have to be low-pass a master layout file, except if your bundle is a complete application.

Translating documents

If the bundle provides information translation, it must be defined in the Xliff format, and the zone name must be named after the bundle name, such as Bundle.hello

Configuration

To provide greater flexibility, a bundle can use Symfony2 's built-in mechanism to provide configuration settings. For simple settings, the parameters configuration portal is dependent on the default Symfony2. The Symfony2 parameters are simple key/value pairs. The value can be any valid PHP value. Each parameter name should start with a false bundle alias, which is only the best recommendation. The remainder of the parameter name is used with a dot (.) segmentation, such as Acme_hello.email.from

Allows end users to provide value information directly in the configuration file.

YAML format:

# app/config/config.ymlparameters:    acme_hello.email.from:fabien@example.com

XML format:

 
  
 
     
  
   
    
   Fabien@example.com
  
   
 
  

PHP Code format:

App/config/config.php$container->setparameter (' Acme_hello.email.from ', ' fabien@example.com ');

INI format:

[Parameters]acme_hello.email.from = fabien@example.com

This allows you to get these configuration information from the container in your code:

$container->getparameter (' Acme_hello.email.from ');

If you define a service, we also recommend that you use the alias of the bundle as a prefix.

Summary thinking:

The above is a general picture of the most important plug-in format bundle in Symfony2, and almost all of the applications that are based on the Symfony2 are composed of bundles. The core components of the Symfony2 itself are frameworkbundle. In the Symfony2 Exchange community, a large number of developers have contributed their bundles, which we can integrate directly into our own applications. Most of the rules mentioned above are the uniform rules that you should follow when you develop your contribution bundle to make it easier for other users to use.

Symfony2 Development Kit for bundles with third-party contributions:

If you are not going to contribute to your bundle, you can do so without following most of the rules here.

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

  • 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.