Home >Backend Development >PHP Tutorial >Detailed explanation of the installation and use of extensions in PHP's Yii framework_php tips

Detailed explanation of the installation and use of extensions in PHP's Yii framework_php tips

WBOY
WBOYOriginal
2016-05-16 19:55:081334browse

扩展是专门设计的在 Yii 应用中随时可拿来使用的, 并可重发布的软件包。例如, yiisoft/yii2-debug 扩展在你的应用的每个页面底部添加一个方便用于调试的工具栏, 帮助你简单地抓取页面生成的情况。 你可以使用扩展来加速你的开发过程。

信息:本文中我们使用的术语 "扩展" 特指 Yii 软件包。而用术语 "软件包" 和 "库" 指代非 Yii 专用的通常意义上的软件包。
使用扩展

要使用扩展,你要先安装它。大多数扩展以 Composer 软件包的形式发布, 这样的扩展可采取下述两个步骤来安装:

修改你的应用的 composer.json 文件,指明你要安装的是哪个扩展 (Composer 软件包)。
运行 composer install 来安装指定的扩展。
注意如果你还没有安装 Composer ,你需要先安装。

默认情况,Composer安装的是在 Packagist 中 注册的软件包 - 最大的开源 Composer 代码库。你可以在 Packageist 中查找扩展。 你也可以 创建你自己的代码库 然后配置 Composer 来使用它。 如果是在开发私有的扩展,并且想只在你的其他工程中共享时,这样做是很有用的。

通过 Composer 安装的扩展会存放在 BasePath/vendor 目录下,这里的 BasePath 指你的应用的 base path。因为 Composer 还是一个依赖管理器,当它安装一个包时, 也将安装这个包所依赖的所有软件包。

例如想安装 yiisoft/yii2-imagine 扩展,可按如下示例修改你的 composer.json 文件:

{
  // ...

  "require": {
    // ... other dependencies

    "yiisoft/yii2-imagine": "*"
  }
}

安装完成后,你应该能在 BasePath/vendor 目录下见到 yiisoft/yii2-imagine 目录。你也应该 见到另一个 imagine/imagine目录,在其中安装了所依赖的包。

信息: yiisoft/yii2-imagine 是 Yii 由开发团队维护一个核心扩展, 所有核心扩展均由 Packagist 集中管理,命名为yiisoft/yii2-xyz,其中的 xyz, 不同扩展有不同名称。
现在你可以使用安装好的扩展了,好比是应用的一部分。如下示例展示了如何使用 yiisoft/yii2-imagine 扩展 提供的yii\imagine\Image 类:

use Yii;
use yii\imagine\Image;

// 生成一个缩略图
Image::thumbnail('@webroot/img/test-image.jpg', 120, 120)
  ->save(Yii::getAlias('@runtime/thumb-test-image.jpg'), ['quality' => 50]);

信息: 扩展类由 Yii class autoloader 自动加载。
手动安装扩展

在极少情况下,你可能需要手动安装一部分或者全部扩展,而不是依赖 Composer。 想做到这一点,你应当:

下载扩展压缩文件,解压到 vendor 目录。
如果有,则安装扩展提供的自动加载器。
按指导说明下载和安装所有依赖的扩展。
如果扩展没有提供类的自动加载器,但也遵循了 PSR-4 standard 标准,那么你可以使用 Yii 提供的类自动加载器来加载扩展类。 你需要做的仅仅是为扩展的根目录声明一个 root alias。 例如,假设在 vendor/mycompany/myext 目录中安装了一个扩展,并且扩展类的命名空间为 myext , 那么你可以在应用配置文件中包含如下代码:

[
  'aliases' => [
    '@myext' => '@vendor/mycompany/myext',
  ],
]

创建扩展

在你需要将你的杰作分享给其他人的时候,你可能会考虑创建一个扩展。 扩展可包括任何你喜欢的代码,例如助手类、挂件、模块,等等。

建议你按照 Composer package 的条款创建扩展,以便其他人更容易安装和使用。 

以下是将扩展创建为一个 Composer 软件包的需遵循的基本步骤。

为你的扩展建一个工程,并将它存放在版本控制代码库中,例如 github.com 。 扩展的开发和维护都应该在这个代码库中进行。
在工程的根目录下,建一个 Composer 所需的名为 composer.json 的文件。
在一个 Composer 代码库中注册你的扩展,比如在 Packagist 中,以便其他 用户能找到以及用 Composer 安装你的扩展。
composer.json

每个 Composer 软件包在根目录都必须有一个 composer.json 文件。该文件包含软件包的元数据。 你可以在 Composer手册 中找到完整关于该文件的规格。 以下例子展示了 yiisoft/yii2-imagine 扩展的 composer.json 文件。

{
  // package name
  "name": "yiisoft/yii2-imagine",

  // package type
  "type": "yii2-extension",

  "description": "The Imagine integration for the Yii framework",
  "keywords": ["yii2", "imagine", "image", "helper"],
  "license": "BSD-3-Clause",
  "support": {
    "issues": "https://github.com/yiisoft/yii2/issues?labels=ext%3Aimagine",
    "forum": "http://www.yiiframework.com/forum/",
    "wiki": "http://www.yiiframework.com/wiki/",
    "irc": "irc://irc.freenode.net/yii",
    "source": "https://github.com/yiisoft/yii2"
  },
  "authors": [
    {
      "name": "Antonio Ramirez",
      "email": "amigo.cobos@gmail.com"
    }
  ],

  // package dependencies
  "require": {
    "yiisoft/yii2": "*",
    "imagine/imagine": "v0.5.0"
  },

  // class autoloading specs
  "autoload": {
    "psr-4": {
      "yii\\imagine\\": ""
    }
  }
}

包名

每个 Composer 软件包都应当有一个唯一的包名以便能从其他的软件包中识别出来。 包名的格式为 vendorName/projectName 。例如在包名 yiisoft/yii2-imagine 中,vendor 名和 project 名分别是 yiisoft 和 yii2-imagine 。

不要用 yiisoft 作为你的 vendor 名,由于它被 Yii 的核心代码预留使用了。

我们推荐你用 yii2- 作为你的包名的前缀,表示它是 Yii 2 的扩展,例如,myname/yii2-mywidget。 这更便于用户辨别是否是 Yii 2 的扩展。

包类型

将你的扩展指明为 yii2-extension 类型很重要,以便安装的时候 能被识别出是一个 Yii 扩展。

当用户运行 composer install 安装一个扩展时, vendor/yiisoft/extensions.php 文件会被自动更新使之包含新扩展的信息。从该文件中, Yii 应用程序就能知道安装了 哪些扩展 (这些信息可通过 yii\base\Application::extensions 访问)。

依赖

你的扩展依赖于 Yii (理所当然)。因此你应当在 composer.json 文件中列出它 (yiisoft/yii2)。如果你的扩展还依赖其他的扩展或者是第三方库,你也要一并列出来。 确定你也为每一个依赖的包列出了适当的版本约束条件 (比如 1.*, @stable) 。 当你发布一个稳定版本时,你所依赖的包也应当使用稳定版本。

大多数 JavaScript/CSS 包是用 Bower 来管理的,而非 Composer。你可使用 Composer asset 插件 使之可以 通过 Composer 来管理这类包。如果你的扩展依赖 Bower 软件包,你可以如下例所示那样简单地 在 composer.json 文件的依赖中列出它。

{
  // package dependencies
  "require": {
    "bower-asset/jquery": ">=1.11.*"
  }
}

上述代码表明该扩展依赖于 jquery Bower 包。一般来说,你可以在 composer.json 中用 bower-asset/PackageName 指定 Bower 包,用 npm-asset/PackageName 指定 NPM 包。 当 Compower 安装 Bower 和 NPM 软件包时,包的内容默认会分别安装到@vendor/bower/PackageName 和 @vendor/npm/Packages 下。这两个目录还可以分别用 @bower/PackageName 和@npm/PackageName 别名指向。

类的自动加载

为使你的类能够被 Yii 的类自动加载器或者 Composer 的类自动加载器自动加载,你应当在 composer.json 中指定 autoload 条目,如下所示:

{
  // ....

  "autoload": {
    "psr-4": {
      "yii\\imagine\\": ""
    }
  }
}

你可以列出一个或者多个根命名空间和它们的文件目录。

当扩展安装到应用中后,Yii 将为每个所列出根命名空间创建一个 别名 指向命名空间对应的目录。 例如,上述的 autoload 条目声明将对应于别名 @yii/imagine。

推荐的做法

扩展意味着会被其他人使用,你在开发中通常需要额外的付出。 下面我们介绍一些通用的及推荐的做法,以创建高品质的扩展。

命名空间

为避免冲突以及使你的扩展中的类能被自动加载,你的类应当使用命名空间, 并使类的命名符合 PSR-4 standard 或者 PSR-0 standard 标准。

你的类的命名空间应以 vendorName\extensionName 起始,其中 extensionName 和项目名相同,除了它没有 yii2- 前缀外。例如,对 yiisoft/yii2-imagine 扩展 来说,我们用 yii\imagine 作为它的类的命名空间。

不要使用 yii、yii2 或者 yiisoft 作为你的 vendor 名。这些名称已由 Yii 内核代码预留使用了。

类的自举引导

有时候,你可能想让你的扩展在应用的 自举过程 中执行一些代码。 例如,你的扩展可能想响应应用的 beginRequest 事件,做一些环境的设置工作。 虽然你可以指导扩展的使用者显式地将你的扩展中的事件句柄附加(绑定)到 beginRequest 事件, 但是更好的方法是自动完成。

为实现该目标,你可以创建一个所谓 bootstrapping class (自举类)实现 yii\base\BootstrapInterface 接口。 例如,

namespace myname\mywidget;

use yii\base\BootstrapInterface;
use yii\base\Application;

class MyBootstrapClass implements BootstrapInterface
{
  public function bootstrap($app)
  {
    $app->on(Application::EVENT_BEFORE_REQUEST, function () {
       // do something here
    });
  }
}

然后你将这个类在 composer.json 文件中列出来,如下所示,

{
  // ...

  "extra": {
    "bootstrap": "myname\\mywidget\\MyBootstrapClass"
  }
}

When this extension is installed in the application, Yii will automatically instantiate the bootstrap class and call its yiibaseBootstrapInterface::bootstrap() method during the bootstrap process of each request.

Operation database

Your extension may need to access a database. Don't assume that applications using your extension will always use Yii::$db as the database connection. You should declare a db attribute in the class that needs to access the database. This property allows users of your extension to customize which DB connection your extension uses. For example, you can refer to the yiicachingDbCache class to see how it declares and uses the db attribute.

If your extension needs to create specific database tables, or modify the database structure, you should

Provide data migration to operate the structural modification of the database instead of using SQL text files;
Try to adapt migration files to different DBMSs;
Avoid using Active Record in migration files.
Use Assets

If your extension is a widget or module type, it may need to use some assets. For example, a module might display pages that contain images, JavaScript, and CSS. Because the extension files are placed in the same directory, they cannot be read by the Web after installation. You have two options to make these asset file directories readable by the Web:

Let the extension user manually copy these asset files to a specific web-readable folder;
Declare an asset bundle and rely on the asset publishing mechanism to automatically copy the files (listed in the asset bundle) to a web-readable folder.
We recommend you use the second method to make it easier for others to use your extension.

Internationalization and localization

Your extension may be used in apps that support different languages! Therefore, if your extension is going to display content to end users, you should try to implement internationalization and localization, in particular,

If the extension displays information for the end user, this information should be wrapped with Yii::t() so that it can be translated. Information only for developers' reference (such as internal exception information) does not need to be translated.
If the extension displays numbers, dates, etc., you should use the appropriate formatting rules in yiii18nFormatter for formatting.

Test

You want your extension to run flawlessly without causing problems and trouble for others. To achieve this goal, you should test it before releasing it to the public.

It is recommended that you create test cases to test your extension with comprehensive coverage instead of just relying on manual testing. Before each release of a new version, you simply run these tests to make sure everything is fine. Yii provides testing support to make it easier for you to write unit tests, acceptance tests, and functional tests.

Version Control

You should give each extension a version number (e.g. 1.0.1). We recommend that you refer to semantic versioning when naming version numbers to decide what version number to use.

Publish

To let others know about your extension, you should publish it publicly.

If you release an extension for the first time, you should register it with a Composer repository such as Packagist. After that, all you need to do is create a tag in the version management repository (such as v1.0.1), and then notify the Composer code base. Others will be able to find the new release and install and update the extension through the Composer repository.

When publishing your extension, in addition to the code files, you should also consider including the following content to help others understand and use your extension:

Readme file in the root directory: It describes what your extension does and how to install and use it. We recommend that you write in Markdown format and name the file readme.md.
Change log file in the root directory: This lists what changes were made for each version of the release. This file can be written in Markdown radical and named changelog.md.
Upgrade file in the root directory: This gives instructions on how to upgrade the extension from other versions. This file can be written in Markdown radical and named changelog.md.
Getting started guide, demo code, screenshots, etc.: These files are used if your extension provides many functions that cannot be fully described in the readme file.
API documentation: Your code should be well documented to make it easier for others to read and understand. You can refer to Object class file to learn how to document your code.
Info: Your code comments can be written in Markdown format. The yiisoft/yii2-apidoc extension provides you with a way to generate beautiful API documentation from your code comments.

Information: Although not required, we recommend that your extension adhere to a coding convention. You can refer to core framework code style.
Core Extensions

Yii provides the following core extensions, developed and maintained by the Yii development team. These extensions are all registered with Packagist:

  • yiisoft/yii2-apidoc: Provides an extensible and efficient API documentation generator. The API documentation for the core framework is also generated using it.
  • yiisoft/yii2-authclient: Provides a set of commonly used authentication clients, such as Facebook OAuth2 client and GitHub OAuth2 client.
  • yiisoft/yii2-bootstrap: Provides a set of widgets that encapsulate Bootstrap components and plug-ins.
  • yiisoft/yii2-codeception: Provides testing support based on Codeception.
  • yiisoft/yii2-debug: Provides debugging support for Yii applications. When using this extension, a debugging toolbar will appear at the bottom of every page. The extension also provides a separate page to display more detailed debugging information.
  • yiisoft/yii2-elasticsearch: Provides support for Elasticsearch. It includes basic query/search support and implements the Active Record mode so you can store active records in Elasticsearch.
  • yiisoft/yii2-faker: Provides support for using Faker to generate simulated data for you.
  • yiisoft/yii2-gii: Provides a page-based code generator that is highly scalable and can be used to quickly generate models, forms, modules, CRUD, etc.
  • yiisoft/yii2-imagine: Provides common image processing functions based on Imagine.
  • yiisoft/yii2-jui: Provides a set of widgets that encapsulate JQuery UI and their interactions.
  • yiisoft/yii2-mongodb: Provides support for MongoDB. It includes basic query, activity logging, data migration, caching, code generation and other features.
  • yiisoft/yii2-redis: Provides support for redis. It includes basic query, activity logging, caching and other features.
  • yiisoft/yii2-smarty: Provides a template engine based on Smarty.
  • yiisoft/yii2-sphinx: Provides support for Sphinx. It includes basic querying, activity logging, code generation and other features.
  • yiisoft/yii2-swiftmailer: Provides email sending function based on swiftmailer.
  • yiisoft/yii2-twig: Provides a template engine based on Twig.
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