Detailed description of PHP Yii Framework extension installation and use

Source: Internet
Author: User
Tags autoload composer install
This article describes how to install and use extensions in the PHP Yii Framework. it lists some core extensions in Yii, you can refer to the software packages that can be used and re-released at any time in Yii applications. For example, the yiisoft/yii2-debug extension adds a toolbar at the bottom of each page of your application for debugging, helping you easily capture page generation situations. You can use extensions to accelerate your development process.

Information: The term "extension" we use in this article refers to the Yii software package. The terms "software packages" and "libraries" refer to software packages that are not specific to Yii in the general sense.
Use extension

To use extensions, install them first. Most extensions are released in the form of a Composer package. such extensions can be installed using the following two steps:

Modify the composer. json file of your application to specify the extension (Composer package) you want to install ).
Run composer install to install the specified extension.
Note that if you have not installed Composer, you need to install it first.

By default, Composer installs the software package registered in Packagist-the largest open-source Composer code library. You can search for extensions in Packageist. You can also create your own code library and configure Composer to use it. This is useful if you are developing private extensions and want to share them only in other projects.

Extensions installed using Composer are stored in the BasePath/vendor Directory. the BasePath here refers to the base path of your application. Because Composer is still a dependency manager, when it installs a package, it also installs all the packages that this package depends on.

For example, to install the yiisoft/yii2-imagine extension, you can modify your composer. json file as follows:

{  // ...  "require": {    // ... other dependencies    "yiisoft/yii2-imagine": "*"  }}

After the installation is complete, you should be able to see the yiisoft/yii2-imagine directory under the BasePath/vendor Directory. You should also see another imagine/imagine directory where the dependent package is installed.

Information: yiisoft/yii2-imagine is a core extension maintained by the development team of Yii, all core extensions are centrally managed by Packagist, named yiisoft/yii2-xyz, where xyz, different extensions have different names.
Now you can use the installed extensions, such as a part of the application. The following example shows how to use the yii \ imagine \ Image class provided by the yiisoft/yii2-imagine extension:

Use Yii; use yii \ imagine \ Image; // Generate a thumbnail Image: thumbnail ('@ webroot/img/test-image.jpg', 120,120)-> save (Yii :: getAlias ('@ runtime/thumb-test-image.jpg'), ['qc '=> 50]);

Information: The extension class is automatically loaded by Yii class autoloader.
Manually install extension

In rare cases, you may need to manually install some or all of the extensions, rather than relying on Composer. To do this, you should:

Download the extended compressed file and decompress it to the vendor directory.
If yes, install the auto-loader provided by the extension.
Download and install all dependent extensions as instructed.
If the extension does not provide an auto-loader for the class, but also follows the PSR-4 standard, you can use the class auto-loader provided by Yii to load the extension class. All you need to do is declare a root alias for the extended root directory. For example, if an extension is installed in the vendor/mycompany/myext directory and the namespace of the extension class is myext, you can include the following code in the application configuration file:

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

Create extension

When you need to share your masterpiece with others, you may consider creating an extension. Extensions can include any code you like, such as helper classes, pendants, modules, and so on.

We recommend that you follow the terms of the Composer package to create extensions so that others can install and use them more easily.

The following are the basic steps to create an extension as a Composer package.

Create a project for your extension and store it in the version control code base, such as github.com. Extension development and maintenance should be carried out in this code library.
In the root directory of the project, create a file named Composer. json required by composer.
Register your extension in a Composer code library, such as in Packagist, so that other users can find and install your extension with Composer.
Composer. json

Each Composer package must have a composer. json file in the root directory. This file contains the metadata of the software package. You can find the complete specification for this file in the Composer manual. The following example shows the composer. json file of the yiisoft/yii2-imagine extension.

{  // 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\\": ""    }  }}

Package name

Each Composer package should have a unique package name for identification from other packages. The package name format is vendorName/projectName. For example, in the package name yiisoft/yii2-imagine, the vendor and project names are yiisoft and yii2-imagine.

Do not use yiisoft as your name because it is reserved for use by Yii's core code.

We recommend that you use yii2-as the prefix of your package name, indicating that it is an extension of Yii 2, for example, myname/yii2-mywidget. This makes it easier for users to identify whether it is an extension of Yii 2.

Package Type

It is important to specify your extension as a yii2-extension type so that it is identified as a Yii extension during installation.

When you run composer install to install an extension, the file vendor/yiisoft/extensions. php is automatically updated to include information about the new extension. From this file, the Yii Application knows which extensions are installed (this information can be accessed through yii \ base \ Application: extensions ).

Dependency

Your extension depends on Yii (of course ). Therefore, you should list it in the composer. json file (yiisoft/yii2 ). If your extension depends on other extensions or third-party libraries, you should also coordinate them. Make sure that you have listed the appropriate version constraints for each dependent package (for example, 1. *, @ stable ). When you release a stable version, you should also use the stable version of the dependent package.

Most JavaScript/CSS packages are managed using Bower instead of Composer. You can use the Composer asset plug-in to enable Composer to manage such packages. If your extension depends on the Bower package, you can simply list it in the dependencies of the composer. json file as shown in the following example.

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

The code above indicates that the extension depends on the jquery Bower package. Generally, you can use bower-asset/PackageName in composer. json to specify the Bower package and use npm-asset/PackageName to specify the NPM package. When Compower installs the Bower and NPM Packages, the package content is installed under @ vendor/bower/PackageName and @ vendor/npm/Packages by default. The two directories can also be pointed to by @ bower/PackageName and @ npm/PackageName aliases respectively.

Automatic loading of classes

To enable your class to be automatically loaded by the Yii automatic class loader or Composer automatic class loader, you should specify the autoload entry in composer. json, as shown below:

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

You can list one or more root namespaces and their file directories.

After the extension is installed in the application, Yii creates an alias for each listed root namespace pointing to the corresponding directory of the namespace. For example, the preceding autoload entry declaration corresponds to the alias @ yii/imagine.

Recommended Practices

Extension means it will be used by others. you usually need to pay extra for development. Next we will introduce some common and recommended practices to create high-quality extensions.

Namespace

To avoid conflicts and enable the classes in your extensions to be automatically loaded, your classes should use namespaces and make the class names conform to PSR-4 standard or PSR-0 standard.

The namespace of your class should start with vendorName \ extensionName. the extensionName and project name are the same except that it does not have the yii2-prefix. For example, for the yiisoft/yii2-imagine extension, we use yii \ imagine as its class namespace.

Do not use yii, yii2, or yiisoft as your name. These names are reserved by Yii kernel code.

Class bootstrap guide

Sometimes, you may want your extension to execute some code during the app's self-lifting process. For example, your extension may want to respond to the beginRequest event of the application and set the environment. Although you can instruct the extension user to explicitly attach (bind) the event handle in your extension to the beginRequest event, a better way is to automatically complete it.

To achieve this goal, you can create a so-called bootstrapping class to implement the yii \ base \ BootstrapInterface interface. For example,

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    });  }}

Then you can list this class in the composer. json file, as shown below,

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

After this extension is installed on the application, Yii will automatically instantiate the UDF class during each request and call its yii \ base \ BootstrapInterface: bootstrap () method.

Database operations

Your extensions may need to access the database. Do not assume that your extended application always uses Yii: $ db as the database connection. You should declare a db attribute in the class to access the database. This attribute allows your extension users to customize which DB connection your extension uses. For example, you can refer to yii \ caching \ DbCache class to see how it declares and uses db attributes.

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

Provides data migration to modify the database structure, rather than using SQL text files;
Try to make the migration file suitable for different DBMS;
Avoid using Active Record in the migration file.
Use Assets

If your extension is a pendant or module type, it may need to use some assets. For example, a module may display pages that contain images, JavaScript, and CSS. Because the extended files are stored in the same directory and cannot be read by the Web after installation, you have two options for these asset file directories to be read through the Web:

Allows an extended user to manually copy these asset files to a folder that can be read on a specific Web;
Declare an asset bundle and use the asset publishing mechanism to automatically copy these files (files listed in the asset bundle) to a Web-readable folder.
We recommend that you use the second method so that others can use your extensions more easily.

Internationalization and localization

Your extensions may be used in applications that support different languages! Therefore, if your extensions want to display content to end users, you should try to achieve internationalization and localization, especially,

If it is extended to display information for end users, the information should be packaged in Yii: t () for translation. You do not need to translate the information referenced by developers only (for example, internal exception information.
If the extended display number and date are displayed, you should use the appropriate Formatter rules in yii \ i18n \ Formatter for formatting.

Test

You must ensure that your extensions can run without any trouble. For this purpose, you should perform a test before the public release.

We recommend that you create test cases and perform full coverage tests for your extension, instead of relying on manual testing. Before each release of a new version, you only need to simply run these test cases to ensure that everything is complete. Yii provides test support, making it easier for you to write unit tests, acceptance tests, and functional tests.

Version control

You should set a version number (for example, 1.0.1) for each extension ). We recommend that you refer to semantic versioning to determine the version number when naming the version number.

Release

To let others know about your extensions, you should publish them publicly.

If you publish an extension for the first time, you should register it in the Composer code library, such as Packagist. After that, you only need to create a tag (such as v1.0.1) in the version management library and then notify the Composer code library. Others can find the new release and install and update the extension through the Composer code library.

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

Readme file in the root directory: it describes what your extension is doing and how to install and use it. We recommend that you use the Markdown format to write and name the file readme. md.
Modify log file in the root directory: it lists the changes made to the release of each version. This file can be written in the Markdown root and named changelog. md.
Upgrade file in the root directory: it provides instructions on how to upgrade the extension from other versions. This file can be written in the Markdown root and named changelog. md.
Getting Started Guide, demo code, screenshot illustration, and so on: if your extension provides many features that cannot be fully described in the readme file, you need to use these files.
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.
Information: your code comments can be written in Markdown format. Yiisoft/yii2-apidoc extensions provide you with a beautiful API documentation generated from your code annotations.

Information: Although not required, we recommend that you follow a certain encoding specification for your extension. You can refer to the core framework code style.
Core extension

Yii provides the following core extensions developed and maintained by the Yii development team. All these extensions are registered in Packagist:

  • Yiisoft/yii2-apidoc: provides a scalable and efficient API documentation builder. The API documentation of the core framework is also generated using it.
  • Yiisoft/yii2-authclient: provides a set of common authentication clients, such as Facebook oau2client, GitHub oau2client.
  • Yiisoft/yii2-bootstrap: provides a set of pendants that encapsulate Bootstrap components and plug-ins.
  • Yiisoft/yii2-codeception: provides Codeception-based testing support.
  • Yiisoft/yii2-debug: provides debugging support for Yii applications. When this extension is used, a debugging toolbar is displayed at the bottom of each page. This extension also provides an independent page to display more detailed debugging information.
  • Yiisoft/yii2-elasticsearch: Elasticsearch support. It includes basic query/search support and implements the Active Record mode, allowing you to store activity records in Elasticsearch.
  • Yiisoft/yii2-faker: provides support for using Faker to generate simulation data for you.
  • Yiisoft/yii2-gii: provides a page-based code generator with high scalability 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 pendants that encapsulate JQuery UI and their interactions.
  • Yiisoft/yii2-mongodb: Provides use support for MongoDB. It includes basic query, activity records, data migration, caching, code generation, and other features.
  • Yiisoft/yii2-redis: provides support for redis. It includes basic query, activity Record, cache, and other features.
  • Yiisoft/yii2-smarty: Provides a Smarty-based template engine.
  • Yiisoft/yii2-sphinx: provides support for the use of Sphinx. It includes basic query, activity records, code generation, and other features.
  • Yiisoft/yii2-swiftmailer: provides swiftmailer-based mail sending capabilities.
  • Yiisoft/yii2-twig: Provides a Twig-based template engine.
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.