Explain the extended installation and use _php techniques in the YII framework of PHP

Source: Internet
Author: User
Tags autoload aliases documentation readable redis reserved composer install yii

Extensions are specially designed to be used at any time in a YII application and can be republished by a software package. For example, the Yiisoft/yii2-debug extension adds a toolbar handy for debugging at the bottom of each page of your application to help you simply crawl the page generation. You can use extensions to speed up your development process.

Info: The term "extension" we use in this article refers specifically to the YII package. The term "packages" and "libraries" are used to refer to the usual software packages that are not dedicated to Yii.
using extension

To use an extension, you have to install it first. Most extensions are published in the form of Composer software packages, and such extensions can be installed in the following two steps:

Modify your application's Composer.json file to indicate which 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 packages that are registered in Packagist-the largest open source Composer code base. You can look for extensions in packageist. You can also create your own code base and configure Composer to use it. This is useful if you are developing a private extension and want to share it only in your other projects.

Extensions that are installed through Composer are stored in the Basepath/vendor directory, where BasePath refers to the base path of your application. Because Composer is also a dependency manager, when it installs a package, it will also install all the packages that the package relies 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 in which to install the dependent packages.

Info: Yiisoft/yii2-imagine is a core extension of Yii maintained by the development team, all core extensions are managed centrally by Packagist, named Yiisoft/yii2-xyz, where XYZ, different extensions have different names.
Now you can use the installed extensions, like 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;

Generates a thumbnail
image::thumbnail (' @webroot/img/test-image.jpg ',->save) (
  yii::getalias (' @runtime/ Thumb-test-image.jpg '), [' Quality ' => 50]);

Info: The extension class is loaded automatically by the Yii class autoloader.
Install extensions manually

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

Download the extended compressed file and extract it into the vendor directory.
If it does, install an extension-provided auto loader.
Follow the instructions to download and install all dependent extensions.
If the extension does not provide the class's auto loader, but also follows the PSR-4 standard standard, you can load the extended class with the class loader provided by Yii. All you have to do is declare a root alias for the extended root directory. For example, suppose that an extension is installed in the Vendor/mycompany/myext directory and the namespace of the extended class is Myext, then you can include the following code in the application configuration file:

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

Create an extension

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

It is recommended that you create extensions in accordance with the terms of Composer package so that others are easier to install and use.

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

Build a project for your extension and store it in the version control code base, such as github.com. The development and maintenance of extensions should be done in this code base.
In the root directory of the project, build a file called Composer.json that Composer requires.
Register your extensions in a Composer code base, such as in packagist, so that other users can find and install your extensions with Composer.
Composer.json

Each Composer package must have a Composer.json file in the root directory. This file contains the metadata for the package. You can find the complete specification of the document in the composer manual. The following example shows the Composer.json file for 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 so that it can be identified from other packages. The package name is formatted as Vendorname/projectname. For example, in the package name Yiisoft/yii2-imagine, the vendor name and project name are Yiisoft and Yii2-imagine respectively.

Do not use Yiisoft as your vendor name because it is reserved for use by the core code of YII.

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

Package Type

It is important to indicate your extension as a yii2-extension type so that it can be identified as a Yii extension when installed.

When a user runs composer install installs an extension, the vendor/yiisoft/extensions.php file is automatically updated to include information about the new extension. From this file, the YII application knows which extensions are installed (this information is accessible through yii\base\application::extensions).

Depend on

Your extension relies on Yii (for granted). So you should list it in the Composer.json file (YIISOFT/YII2). If your extensions are dependent on other extensions or Third-party libraries, you should also have them listed. Make sure you also list the appropriate version constraints (such as 1.*, @stable) for each dependent package. When you release a stable version, the package you rely on should also use a stable version.

Most JAVASCRIPT/CSS packages are managed with Bower, not Composer. You can use the Composer asset plugin to make it possible to manage such packages through Composer. If your extension relies 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 above code indicates that the extension relies on the jquery Bower package. In general, you can specify the bower package in the Composer.json with Bower-asset/packagename, and specify the NPM package with Npm-asset/packagename. When Compower installs Bower and NPM packages, the contents of the package are installed by default to the @vendor/bower/packagename and @vendor/npm/packages respectively. The two directories can also be pointed to @bower/PackageName and @npm/packagename aliases, respectively.

Automatic loading of classes

To enable your class to be automatically loaded by the class auto loader of Yii or Composer, you should specify the AutoLoad entry in Composer.json, as follows:

{
  // ....

  " AutoLoad ': {' psr-4 ':
    {
      ' yii\\imagine\\ ': ' '}}
}

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

When the extension is installed in the application, Yii creates an alias for each of the listed root namespaces to the directory corresponding to the namespace. For example, the above AutoLoad entry declaration corresponds to the alias @yii/imagine.

Recommended Practices

Scaling means being used by others, and you usually need to pay extra for development. Here are some common and recommended practices to create high quality extensions.

Name space

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

The namespace of your class should start with Vendorname\extensionname, where ExtensionName is the same as the project name, except that it has no yii2-prefix. For example, for yiisoft/yii2-imagine extensions, we use Yii\imagine as the namespace for its classes.

Do not use Yii, YII2 or Yiisoft as your vendor name. These names have been reserved for use by the Yii kernel code.

Self-Bootstrap of class

Sometimes, you may want your extension to execute some code in the application's bootstrap process. For example, your extension may want to respond to the application of the BeginRequest event and do some setup work for the environment. Although you can instruct an extended user to explicitly append (BIND) an event handle in your extension to the BeginRequest event, a better way is to automate it.

To achieve this goal, you can create a so-called bootstrapping class (bootstrap) 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 () {
       //does something here
    });
  }


You then list the class in the Composer.json file, as shown below,

{
  // ...

  " Extra ': {
    ' bootstrap ': ' Myname\\mywidget\\mybootstrapclass '
  }
}

When this extension is installed to the application, Yii automatically instantiates the bootstrap class and invokes its Yii\base\bootstrapinterface::bootstrap () method during each request's bootstrap process.

manipulating databases

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

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

Provides data migration to manipulate database structure modifications rather than using SQL text files;
Try to make the migration file applicable to different DBMS;
Avoid using Active record in the migration file.
using Assets

If your extension is a pendant or a module type, it may be necessary to use some assets. For example, a module might want to display some pages that contain pictures, JavaScript, and CSS. Since the extended files are all placed under the same directory and the Web cannot be read after installation, you have two choices to make these asset file directories readable by the Web:

Allow extended users to manually copy these asset files to a specific Web-readable folder;
Declare a asset bundle and rely on the asset publishing mechanism to automatically copy these files (the files listed in asset bundle) to a Web-readable folder.
We recommend that you use the second method so that other people can use your extensions more easily.

Internationalization and Localization

Your extensions may be used in applications that support different languages! Therefore, if your extension is to display content to end users, you should try to internationalize and localize, especially

If the extension is for end user display information, the information should be wrapped in yii::t () so that it can be translated. Information that is only referred to the developer (such as internal exception information) does not need to be translated.
If the extension displays numbers, dates, and so on, you should format them with the appropriate formatting rules in Yii\i18n\formatter.

Test

You must want your extension to run flawlessly without causing problems and trouble to others. To achieve this, you should test before public release.

It is recommended that you create test cases, do a comprehensive coverage of your extensions, and not just rely on manual testing. Each time you release a new version, you simply run these test cases to make sure everything is fine. YII provides test support that makes it easier for you to write unit tests, acceptance tests, and functional tests.

Version control

You should set a version number (such as 1.0.1) for each extension. We recommend you to name the version number when referencing semantic versioning decide what version number to use.

Release

To make other people aware of your expansion, you should publish it publicly.

If you publish an extension for the first time, you should register it in the Composer code base, such as Packagist. After that, all you need to do is create a tag (such as v1.0.1) in the version Management library, 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 code base.

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

The Readme file in the root directory: it describes what your extension is and how it is installed and used. We recommend that you write in markdown format and name the file readme.md.
The change log file in the root directory: It enumerates what changes have been made to the release of each version. The file can be written with a markdown radical and named Changelog.md.
The upgrade file in the root directory: It gives guidance on how to upgrade the extension from other versions. The file can be written with a markdown radical and named Changelog.md.
Getting Started, demo code, screenshots, and more: If your extension provides a lot of functionality, you'll need to use these files when you can't fully describe them in the Readme file.
API Documentation: Your code should be well documented to make it easier for others to read and understand. You can learn how to document your code with reference to Object class file.
Info: Your code comments can be written in markdown format. The Yiisoft/yii2-apidoc extension provides you with a beautiful API document from your code comments.

Information: Although not required, we recommend that your extensions follow an encoding specification. You can refer to the 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 in Packagist:

  • Yiisoft/yii2-apidoc: Provides an extensible and efficient API documentation generator. The core framework's API documentation is also generated with it.
  • Yiisoft/yii2-authclient: Provides a set of commonly used authentication clients, such as Facebook OAuth2 client, GitHub OAuth2 client.
  • Yiisoft/yii2-bootstrap: Provides a set of pendants that encapsulates the bootstrap components and plug-ins.
  • Yiisoft/yii2-codeception: Provides test support based on Codeception.
  • Yiisoft/yii2-debug: Provides debugging support for YII applications. When you use this extension, a debug bar appears at the bottom of each page. The extension also provides a separate page to display more detailed debugging information.
  • Yiisoft/yii2-elasticsearch: Provides support for the use of Elasticsearch. It contains basic query/search support and implements active record mode so that you can store activity records in Elasticsearch.
  • Yiisoft/yii2-faker: Provides support for using Faker to generate analog 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, and more.
  • Yiisoft/yii2-imagine: Provides a common image processing function based on imagine.
  • Yiisoft/yii2-jui: Provides a set of pendants that encapsulate the JQuery UI and their interactions.
  • YIISOFT/YII2-MONGODB: Provides support for the use of MongoDB. It contains features such as basic queries, activity records, data migrations, caching, code generation, and so on.
  • Yiisoft/yii2-redis: Provides support for the use of Redis. It contains features such as basic queries, active records, caching, and so on.
  • Yiisoft/yii2-smarty: Provides a template engine based on Smarty.
  • Yiisoft/yii2-sphinx: Provides support for the use of Sphinx. It contains features such as basic queries, activity records, code generation, and so on.
  • Yiisoft/yii2-swiftmailer: Provides a swiftmailer based mail delivery feature.
  • Yiisoft/yii2-twig: Provides a template engine based on twig.
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.