Home  >  Article  >  Backend Development  >  Detailed explanation of Symfony2 plug-in format

Detailed explanation of Symfony2 plug-in format

*文
*文Original
2018-01-05 17:47:391545browse

This article mainly introduces the plug-in format of Symfony2, and analyzes in detail the plug-in principle of Symfony2 and related techniques for creating and using plug-ins. Friends in need can refer to it. I hope it will be helpful to everyone.

A bundle is similar to a plug-in in other frameworks, but performs better than a plug-in. The main difference from other frameworks is that everything in Symfony2 is a bundle, including core framework functions and all application code you write. In Symfony2, bundles are first-class citizens. This gives you more flexibility to use content packages developed by other third parties or distribute your own bundles. You can easily choose what to apply to your program and what not to optimize them according to your ideas.

A bundle is a directory, which has a very good structure and can store anything from classes to controllers and web resources.

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

You can create a BlogBundle, a ForumBundle or a bundle that implements user management (it seems that there are already many such open source bundles). Each bundle directory contains everything related to the implementation content, including PHP files, templates, style sheets, javascript files, test content, and anything else related. All aspects of the content to be implemented are kept in a bundle.

An application is composed of all bundles defined in the registerBundles() method in the AppKernel class.

// app/AppKernel.php
public 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 uniformly control and manage your application components.

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

Create a bundle

The standard version of Symfony2 has prepared a full-featured bundle creation tool file for you. You can run it to create all the contents of the bundle, or you can

choose to create it manually. Now we create an AcmeTestBundle and make it work in our application. Note that Acme here is a fake provider name. You can completely replace it with the name of your own organization or company.

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, to make it available in your application, you need to add it in the AppKernel class Add it in the registerBundles() method.

// app/AppKernel.php
public function registerBundles()
{
  $bundles = array(
    // ...
    // register your bundles
    new Acme\TestBundle\AcmeTestBundle(),
  );
  // ...
  return $bundles;
}

Although it can't do anything now, it has become part of your application.

We can also use the command line tools provided by Symfony2 to create:

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

If you use the above command line tools, the created bundle will automatically be registered in the appKernel class.

Bundle directory structure

Look at the directory structure of the Demo bundle that comes with our Symfony2:

The directory structure of the bundle is simple and flexible, as you can see from the screenshot above:

Controller/ contains all controllers files of the bundle, such as HelloController.php.
DependencyInjection/ holds specific dependency injection extension classes that may import service configurations, register compiler transports, or more. This directory is not required.
Resources/config/ stores configuration files, including routing configuration (for example: routing.yml).
Resources/views/ All templates are divided into folders according to the names of the corresponding controllers and saved here. For example Hello/index.html.twig.
Resources/public/ All accessible web resources (images, style sheets, etc.) and the contents copied or asynchronously linked to the project web/ directory through the assets:install console command.
Tests/ Save all tests in the bundle

The following are some standard rules for bundles recommended by Symfony2:

Bundle name:

a Bundle is also a PHP namespace. Namespaces must comply with PHP5.3's internal technical standards for namespaces and class names. Use the provider name at the beginning, followed by the classification segment (can be omitted), and finally the abbreviated name of the namespace, and the name must be suffixed with Bundle. To turn a namespace into a bundle, you only need to add a bundle class to the namespace.

Bundle class naming:

Only numbers, letters and underscores are applicable
Use camel case naming
Use a descriptive and concise name (no more than two characters) words)
Use the supplier name as a prefix (optional classification namespace)

Add Bundle as a name suffix

For example:

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 abbreviated version of the bundle name in lowercase characters, separated by underscores. For example, the original name of acme_hello's bundle is AcmeHelloBundle, and acme_social_blog is an instance of Acme\Social\BlogBundle.

The alias must be unique in a bundle.

Bundle’s directory structure: HelloBundle’s basic directory structure

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

上面的XXX/... 映射到该bundle的命名空间。其中下面的文件是必备的:

HelloBundle.php;

Resources/meta/LICENSE: 全文的许可代码;
Resources/doc/index.rst: bundle说明的根目录文件。

使用类的子文件夹的深度应该保持到最小(2级是极限)。如果更多级可以定义为非静态,不过很少使用。bundle的目录是只读的。如果你需要修改临时文件,把它们保存到主应用程序的cache/ 或者 log/ 目录下。

需要强调的类和文件

类型 VS 目录

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/

类:

bundle的目录结构是被用来当作命名空间层级的。比如HelloController类保存在 Bundle/HelloBundle/Controller/HelloController.php文件中。

所以类的完全限定名是 Bundle\HelloBundle\Controller\HelloController 。 一些类被看作是装饰,应该越短越好,比如Commands,Helpers, Listeners 和Controllers等,一般都会被当作后缀。

跟事件分发器有关的类应该用后缀Listener标识。

异常类应该保存到一个Exception子命名空间中。

关于提供商

一个bundle不应该被嵌入第三方的PHP类库,它应该依靠Symfony2标准来自动加载它们。

一个bundle不应该被嵌入第三方的javascript,CSS或者其它语言写的任何类库。

关于测试

一个bundle应该有一个使用PHPUnit的测试单元并把它存储在Tests/ 目录下。

测试应该遵循以下原则:

测试套件必须能够被一个简单的phpunit 命令从一个简单的应用程序中执行。

功能测试应该只备用来测试回复输出和一些监控信息。

测试代码覆盖应该至少在95%以上的基本代码。

一个测试套件可以不包含AllTests.php脚本,但必须依靠外部的phpunit.xml.dist文件。

文档说明

所有的类必须带有PHPDoc。

Controllers

最好的情况下,controller应该在一个可以部署到其它地方的bundle中,那么它不能继承Controller基类。而是通过实现ContainerAwareInterface接口或者继承ContainerAware来取代继承Controller。

Routing

如果bundle提供路由,他们必须使用bundle的别名为前缀,比如一个AcmeBlogBundle实例,所有的路由名必须是acme_blog_ 开头。

Templates

如果bundle提供模板,它必须使用Twig。 bundle不必低通一个主布局文件,如果你的bundle是一个完整的应用程序除外。

翻译文件

如果bundle提供信息翻译,它必须是被定义成XLIFF格式,区域名必须被命名在bundle名字之后,如bundle.hello

配置

为了提供更大的灵活性,一个bundle可以使用Symfony2的内建机制提供配置设置。对于简单的设置,依赖于默认的Symfony2的parameters配置入口。 Symfony2参数都是简单的 key/value 对。值可以是任意的合法的PHP值。 每个参数名应该以讹bundle的别名开始,这只是一个最佳的建议。参数名其余部分用点号(.)分割,比如 acme_hello.email.from

让最终用户可以在配置文件中直接提供值信息。

YAML格式:

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

XML格式:

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

PHP代码格式:

// app/config/config.php
$container->setParameter(&#39;acme_hello.email.from&#39;, &#39;fabien@example.com&#39;);

INI格式:

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

这样就可以在代码中从容器获取这些配置信息了:

$container->getParameter(&#39;acme_hello.email.from&#39;);

如果你定义服务,我们也推荐你使用bundle的别名作为前缀。

总结思考:

以上是关于Symfony2中最主要的插件格式bundle的大体情况,在整个Symfony2为基础开发的应用程序中,几乎全部都是有bundle组成。Symfony2本身的核心组件都是FrameworkBundle。在Symfony2交流社区中,已经有了大量的开发者贡献了他们的bundle,我们可以直接拿来集成到我们自己的应用程序中使用。上面所说的大部分规则,都是应用于你开发贡献bundle时应该遵循的统一规则,以方便其它用户使用。

带有第三方贡献的bundle的Symfony2开发包:

如果你不打算把你的bundle贡献出来,那么完全可以不用按照这里说的大部分规则进行开发。

相关推荐:

详解Symfony模板快捷变量的用法

详解Symfony在模板和行为中取得request参数的方法

简述Symfony核心类

The above is the detailed content of Detailed explanation of Symfony2 plug-in format. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn