Symfony2 Study Notes plugin format analysis, symfony2 Study Notes

Source: Internet
Author: User
Tags configuration settings

Symfony2 Study Notes plugin format analysis, symfony2 Study Notes

This article describes the Symfony2 plug-in format. We will share this with you for your reference. The details are as follows:

A bundle is similar to a plug-in other frameworks, but it performs better than a plug-in. The main difference between it and other frameworks is that everything in Symfony2 is bundle, including core framework functions and all application code you write. In Symfony2, bundle is a first-class citizen. This gives you more flexibility to use content packages developed by other third parties or to distribute your own bundle. You can easily select the content that can be applied to your program and optimize it based on your ideas.

A bundle is a directory with good structure. It can store everything from class to controller and web resources.

A bundle is just a set 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 bundle ). Each bundle directory contains everything related to the implementation content, including the PHP file, template, style sheet, javascript file, test content, and anything else. All aspects of the content to be implemented are stored in a bundle.

An application is composed of all 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\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 centrally control and manage your application composition.

A bundle can be stored in any directory. It can be automatically loaded by configuring the auto loader in the app/autoload. php file.

Create a bundle

In the Symfony2 Standard Edition, you have prepared a full-Function Tool file for creating bundle. You can run it to create all the contents of the bundle. Of course, you can also

Select create by yourself. Now we create an AcmeTestBundle and enable it to work in our applications. Note that the Acme here is a false provider name. You can replace it with your own organization or company name.

First, create a src/Acme/TestBundle/directory and add the 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 to 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 cannot do anything now, it has become part of your application.

We can also use Symfony2 to create a command line tool for us:

$ php app/console generate:bundle --namespace=Acme/TestBundle

If you use the preceding command line tool, the created bundle is automatically registered to the appKernel class.

Bundle directory structure

Let's take a look at the directory structure of the Demo bundle that comes with Symfony2:


Bundle's directory structure is simple and flexible, as shown in the preceding figure:

Controller/All controllers files containing bundle, such as HelloController. php.
DependencyInjection/saves a specific dependency injection extension class, which may import service configurations, register the compiler for transmission, or more. This directory is not required.
Resources/config/stores the configuration file, including route configuration (for example, routing. yml ).
Resources/views/all templates are divided into folders according to the name of the corresponding controller and saved here. For example, Hello/index.html. twig.
Resources/public/all accessible web Resources (images, style sheets, etc.) and content that is asynchronously linked to the project web/directory by running the assets: install console command.
Tests/save all the Tests of bundle

Below are some standard bundle rules recommended by Symfony2:

Bundle Name:

A bundle is also a PHP namespace. The namespace must comply with the internal technical standards of the PHP5.3 namespace and class name. Start with the provider name, followed by the category segment (which can be omitted), and finally the abbreviated namespace name. The name must be suffixed with Bundle. To change a namespace to a bundle, you only need to add a bundle class to the namespace.

Bundle Class Name:

Only numbers, letters, and underscores are allowed.
Use the camper name
Use a descriptive and concise name (no more than two words)
Prefix with vendor name (optional classification namespace)

Add Bundle as name suffix

For example:

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. It is the bundle name in the simplified lowercase character version and is separated by underscores. For example, the bundle of acme_hello is named "AcmeHelloBundle", and "acme_social_blog" is an instance of "Acme \ Social \ BlogBundle.

Aliases must be unique in a bundle.

Bundle directory structure: the Basic directory structure of HelloBundle

XXX/...  HelloBundle/    HelloBundle.php    Controller/    Resources/      meta/        LICENSE      config/      doc/        index.rst      translations/      views/      public/    Tests/

The above XXX/... maps to the namespace of the bundle. The following files are required:

HelloBundle. php;

Resources/meta/LICENSE: Full-text LICENSE code;
Resources/doc/index. rst: Specifies the root directory file of bundle.

The depth of subfolders of classes should be kept to a minimum (level 2 is the limit ). More levels can be defined as non-static, but rarely used. The bundle directory is read-only. If you need to modify temporary files, save them to the cache/or log/directory of the main application.

Classes and files to be emphasized

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 directory structure is used as the namespace level. For example, the HelloController class is saved in the Bundle/HelloBundle/Controller/HelloController. php file.

Therefore, the full name of the class is Bundle \ HelloBundle \ Controller \ HelloController. Some classes are regarded as decoration, and the shorter the better, such as Commands, Helpers, Listeners, and Controllers, are generally treated as suffixes.

Classes related to the event distributor should be identified with the suffix Listener.

The Exception class should be saved to an Exception sub-namespace.

About providers

A bundle should not be embedded in a third-party PHP class library. It should be automatically loaded Based on the Symfony2 standard.

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

Test

A bundle should have a test unit using PHPUnit and store it in the Tests/directory.

The test should follow the following principles:

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

Function Testing should only be used to test the response output and some monitoring information.

The test code should cover at least 95% of the basic code.

A test suite may not contain the AllTests. php script, but it must rely on external phpunit. xml. dist files.

Document Description

All classes must contain PHPDoc.

Controllers

In the best case, the controller should be in a bundle that can be deployed elsewhere, so it cannot inherit the Controller base class. Instead, you can inherit the Controller by implementing the ContainerAwareInterface interface or inheriting ContainerAware.

Routing

If bundle provides routes, they must use the bundle alias as the prefix. For example, if an AcmeBlogBundle instance is used, all Route names must start with acme_blog.

Templates

If bundle provides a template, it must use Twig. Bundle does not need to be downgraded to a master layout file, unless your bundle is a complete application.

Translate files

If a bundle provides information translation, it must be defined in XLIFF format, and the region name must be named after the bundle name, such as bundle. hello.

Configuration

To provide greater flexibility, a bundle can use the built-in mechanism of Symfony2 to provide configuration settings. Simple settings depend on the default Symfony2 parameters Configuration entry. The Symfony2 parameter is a simple key/value pair. The value can be any valid PHP value. Each parameter name should start with the alias of bundle. This is only the best recommendation. The remaining parts of the parameter name are separated by the dot (.), for example, acme_hello.email.from

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

YAML format:

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

XML format:

<!-- app/config/config.xml --><parameters>   <parameter key="acme_hello.email.from">fabien@example.com</parameter></parameters>

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

In this way, you can get the configuration information from the container in the Code:

$container->getParameter('acme_hello.email.from');

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

Summary:

The above is the general situation of bundle, the most important plug-in format in Symfony2. Almost all of the applications developed based on Symfony2 are composed of bundle. The core components of Symfony2 are FrameworkBundle. In the Symfony2 communication community, a large number of developers have contributed to their bundle. We can directly integrate them into our own applications. Most of the rules mentioned above are applicable to the unified rules you should follow when developing the contribution bundle to facilitate other users.

Symfony2 development kit with third-party contribution:


If you are not planning to contribute your bundle, you do not need to develop it according to most of the rules described here.

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

Articles you may be interested in:
  • Symfony2 joint query Implementation Method
  • Symfony2 create page instance details
  • Analysis on date usage in twig of symfony2.4
  • Session and cookie usage in Symfony2
  • Symfony2 framework learning notes
  • System Route details for Symfony2 Study Notes
  • A detailed explanation of the controller usage of Symfony2 learning notes
  • Template usage of Symfony2 learning notes
  • How to install a third-party Bundles instance in Symfony2
  • Symfony2 function usage Example Analysis


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.