SYMFONY2 Learning Notes Plug-in format analysis _php instance

Source: Internet
Author: User
Tags aliases configuration settings php class php code

This article describes the plug-in format for Symfony2. Share to everyone for your reference, specific as follows:

A bundle is similar to plug-ins in other frameworks, but better than plug-ins. The main difference with other frameworks is that everything in Symfony2 is bundle, including the core framework features and all the application code you write. In Symfony2, bundle is a first-class citizen. This gives you more flexibility to use the content packages developed by other third parties or distribute your own bundle. You can easily choose which content can be applied to your program without having to optimize them according to your ideas.

A bundle is a directory, it has a good structure, it can store everything from class to controller and Web resources.

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

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

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

app/appkernel.php Public Function Registerbundles () {$bundles = array (new Symfony\bundle\frameworkbundle\frame
    Workbundle (), New Symfony\bundle\securitybundle\securitybundle (), New Symfony\bundle\twigbundle\twigbundle (), New Symfony\bundle\monologbundle\monologbundle (), New Symfony\bundle\swiftmailerbundle\swiftmailerbundle (), New Sy Mfony\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 the control and management of your application composition.

A bundle can be stored in any directory, and it only needs to be automatically loaded by configuring an automatic loader in the app/autoload.php file.

Create a bundle

The SYMFONY2 Standard Edition has prepared a full-featured tool file for you to create bundle. You can run it to create all the content of bundle, and of course you can

Choose to create yourself manually. Now we create a acmetestbundle and let it work in our applications. Note that Acme here is a fake 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.php
namespace Acme\testbundle;
Use Symfony\component\httpkernel\bundle\bundle;
Class Acmetestbundle extends Bundle
{
}

Next, make it available in your application, you need to add it to the Registerbundles () method in the Appkernel class.

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

Although it cannot do anything now, it has become a 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 bundle that you create are automatically registered in the Appkernel class.

Directory Structure of Bundle

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

Bundle's directory organization is simple and flexible, as you can see from the screenshot above:

controller/contains all controllers files for bundle, such as hellocontroller.php.
Dependencyinjection/saves a specific dependency injection extension class that may import service configurations, register compiler transmissions, or more. This directory is not required.
resources/config/stores configuration files, including routing configuration (e.g., ROUTING.YML).
resources/views/all templates are stored in folders according to the name of the corresponding controller. Like Hello/index.html.twig.
resources/public/all accessible Web resources (Pictures, stylesheets, etc.) and content that is copied or asynchronously linked to the project web/directory via the assets:install console command.
tests/Save Bundle all the tests

The following are some of the Standard Rules for bundle recommended by Symfony2:

Bundle Name:

A bundle is also a PHP namespace. namespaces must adhere to the internal technical standards of PHP5.3 namespaces and class names. The beginning uses 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 bundle as a suffix. A namespace becomes a bundle you just need to add a bundle class to the namespace.

Name of the bundle class:

Only numbers, letters and underscores are available
Using hump-style naming
Use a descriptive concise name (no more than two words)
Prefix with vendor name (Optional category namespace)

Add bundle as name suffix

Like what:

Namespace => Bundle class name

Acme\bundle\blogbundle => acmeblogbundle
acme\bundle\social\blogbundle =>acmesocialblogbundle
Acme\ 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 of the abbreviated version of lowercase characters, which is split with an underscore. For example, Acme_hello's bundle formerly known as Acmehellobundle, Acme_social_blog is an example of acme\social\blogbundle.

Aliases must be unique in a bundle.

Bundle directory Structure: Hellobundle base directory Structure


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

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

hellobundle.php;

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

The depth of the subfolder using the class should be kept to a minimum (level 2 is the limit). If more levels can be defined as non-static, they are 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 that need 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 a namespace-level. For example, the Hellocontroller class is saved in a bundle/hellobundle/controller/hellocontroller.php file.

So the fully qualified name of the class is Bundle\hellobundle\controller\hellocontroller. Some classes are seen as decorations, and the shorter the better, such as Commands,helpers, Listeners and controllers, will generally be treated as suffixes.

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

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

About the provider

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 a third party's javascript,css or any class library written in other languages.

About testing

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

The test should follow the following guidelines:

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

Functional testing should only be prepared to test the response output and some monitoring information.

Test code overrides should be at least 95% of the base code.

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

Document description

All classes must be phpdoc.

Controllers

In the best case, controller should be in a bundle that can be deployed elsewhere, so it cannot inherit controller base classes. Instead of inheriting controller by implementing the Containerawareinterface interface or inheriting the Containeraware.

Routing

If bundle provides routing, they must prefix with bundle aliases, such as a Acmeblogbundle instance, where all routing names must begin with Acme_blog_.

Templates

If bundle provides a template, it must use twig. Bundle does not have to be low on a master layout file, except if your bundle is a complete application.

Translation documents

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

Configuration

To provide greater flexibility, a bundle can use the SYMFONY2 built-in mechanism to provide configuration settings. For simple settings, it relies on the default Symfony2 parameters configuration entry. Symfony2 parameters are simple key/value pairs. The value can be any valid PHP value. Each parameter name should start with a bundle alias, which is just one of the best suggestions. The remainder of the parameter name is the point number (.) Split, like Acme_hello.email.from.

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

YAML format:

# app/config/config.yml
parameters:
    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

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 a bundle alias as a prefix.

Summary thinking:

The above is about the main plug-in format in Symfony2 bundle general situation, in the entire Symfony2 for the development of the application, almost all are bundle composition. The core components of Symfony2 itself are frameworkbundle. In the SYMFONY2 communication community, there are a number of developers who have contributed their bundle, and we can use them directly to integrate into our own applications. Most of the rules mentioned above apply to the uniform rules that you should follow when you develop your contribution to bundle, so that it is easy for other users to use.

Bundle's Symfony2 development package with Third-party contributions:

If you are not going to contribute to your bundle, you may not have to follow most of the rules described here.

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.