


Detailed explanation of the installation and use of extensions in PHP's Yii framework, yii framework_PHP tutorial
Jul 12, 2016 am 08:55 AM詳解PHP的Yii框架中擴(kuò)展的安裝與使用,yii框架
擴(kuò)展是專門設(shè)計(jì)的在 Yii 應(yīng)用中隨時(shí)可拿來使用的, 并可重發(fā)布的軟件包。例如, yiisoft/yii2-debug 擴(kuò)展在你的應(yīng)用的每個(gè)頁(yè)面底部添加一個(gè)方便用于調(diào)試的工具欄, 幫助你簡(jiǎn)單地抓取頁(yè)面生成的情況。 你可以使用擴(kuò)展來加速你的開發(fā)過程。
信息:本文中我們使用的術(shù)語 "擴(kuò)展" 特指 Yii 軟件包。而用術(shù)語 "軟件包" 和 "庫(kù)" 指代非 Yii 專用的通常意義上的軟件包。
使用擴(kuò)展
要使用擴(kuò)展,你要先安裝它。大多數(shù)擴(kuò)展以 Composer 軟件包的形式發(fā)布, 這樣的擴(kuò)展可采取下述兩個(gè)步驟來安裝:
修改你的應(yīng)用的 composer.json 文件,指明你要安裝的是哪個(gè)擴(kuò)展 (Composer 軟件包)。
運(yùn)行 composer install 來安裝指定的擴(kuò)展。
注意如果你還沒有安裝 Composer ,你需要先安裝。
默認(rèn)情況,Composer安裝的是在 Packagist 中 注冊(cè)的軟件包 - 最大的開源 Composer 代碼庫(kù)。你可以在 Packageist 中查找擴(kuò)展。 你也可以 創(chuàng)建你自己的代碼庫(kù) 然后配置 Composer 來使用它。 如果是在開發(fā)私有的擴(kuò)展,并且想只在你的其他工程中共享時(shí),這樣做是很有用的。
通過 Composer 安裝的擴(kuò)展會(huì)存放在 BasePath/vendor 目錄下,這里的 BasePath 指你的應(yīng)用的 base path。因?yàn)?Composer 還是一個(gè)依賴管理器,當(dāng)它安裝一個(gè)包時(shí), 也將安裝這個(gè)包所依賴的所有軟件包。
例如想安裝 yiisoft/yii2-imagine 擴(kuò)展,可按如下示例修改你的 composer.json 文件:
{ // ... "require": { // ... other dependencies "yiisoft/yii2-imagine": "*" } }
安裝完成后,你應(yīng)該能在 BasePath/vendor 目錄下見到 yiisoft/yii2-imagine 目錄。你也應(yīng)該 見到另一個(gè) imagine/imagine目錄,在其中安裝了所依賴的包。
信息: yiisoft/yii2-imagine 是 Yii 由開發(fā)團(tuán)隊(duì)維護(hù)一個(gè)核心擴(kuò)展, 所有核心擴(kuò)展均由 Packagist 集中管理,命名為yiisoft/yii2-xyz,其中的 xyz, 不同擴(kuò)展有不同名稱。
現(xiàn)在你可以使用安裝好的擴(kuò)展了,好比是應(yīng)用的一部分。如下示例展示了如何使用 yiisoft/yii2-imagine 擴(kuò)展 提供的yii\imagine\Image 類:
use Yii; use yii\imagine\Image; // 生成一個(gè)縮略圖 Image::thumbnail('@webroot/img/test-image.jpg', 120, 120) ->save(Yii::getAlias('@runtime/thumb-test-image.jpg'), ['quality' => 50]);
信息: 擴(kuò)展類由 Yii class autoloader 自動(dòng)加載。
手動(dòng)安裝擴(kuò)展
在極少情況下,你可能需要手動(dòng)安裝一部分或者全部擴(kuò)展,而不是依賴 Composer。 想做到這一點(diǎn),你應(yīng)當(dāng):
下載擴(kuò)展壓縮文件,解壓到 vendor 目錄。
如果有,則安裝擴(kuò)展提供的自動(dòng)加載器。
按指導(dǎo)說明下載和安裝所有依賴的擴(kuò)展。
如果擴(kuò)展沒有提供類的自動(dòng)加載器,但也遵循了 PSR-4 standard 標(biāo)準(zhǔn),那么你可以使用 Yii 提供的類自動(dòng)加載器來加載擴(kuò)展類。 你需要做的僅僅是為擴(kuò)展的根目錄聲明一個(gè) root alias。 例如,假設(shè)在 vendor/mycompany/myext 目錄中安裝了一個(gè)擴(kuò)展,并且擴(kuò)展類的命名空間為 myext , 那么你可以在應(yīng)用配置文件中包含如下代碼:
[ 'aliases' => [ '@myext' => '@vendor/mycompany/myext', ], ]
創(chuàng)建擴(kuò)展
在你需要將你的杰作分享給其他人的時(shí)候,你可能會(huì)考慮創(chuàng)建一個(gè)擴(kuò)展。 擴(kuò)展可包括任何你喜歡的代碼,例如助手類、掛件、模塊,等等。
建議你按照 Composer package 的條款創(chuàng)建擴(kuò)展,以便其他人更容易安裝和使用。
以下是將擴(kuò)展創(chuàng)建為一個(gè) Composer 軟件包的需遵循的基本步驟。
為你的擴(kuò)展建一個(gè)工程,并將它存放在版本控制代碼庫(kù)中,例如 github.com 。 擴(kuò)展的開發(fā)和維護(hù)都應(yīng)該在這個(gè)代碼庫(kù)中進(jìn)行。
在工程的根目錄下,建一個(gè) Composer 所需的名為 composer.json 的文件。
在一個(gè) Composer 代碼庫(kù)中注冊(cè)你的擴(kuò)展,比如在 Packagist 中,以便其他 用戶能找到以及用 Composer 安裝你的擴(kuò)展。
composer.json
每個(gè) Composer 軟件包在根目錄都必須有一個(gè) composer.json 文件。該文件包含軟件包的元數(shù)據(jù)。 你可以在 Composer手冊(cè) 中找到完整關(guān)于該文件的規(guī)格。 以下例子展示了 yiisoft/yii2-imagine 擴(kuò)展的 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\\": "" } } }
包名
每個(gè) Composer 軟件包都應(yīng)當(dāng)有一個(gè)唯一的包名以便能從其他的軟件包中識(shí)別出來。 包名的格式為 vendorName/projectName 。例如在包名 yiisoft/yii2-imagine 中,vendor 名和 project 名分別是 yiisoft 和 yii2-imagine 。
不要用 yiisoft 作為你的 vendor 名,由于它被 Yii 的核心代碼預(yù)留使用了。
我們推薦你用 yii2- 作為你的包名的前綴,表示它是 Yii 2 的擴(kuò)展,例如,myname/yii2-mywidget。 這更便于用戶辨別是否是 Yii 2 的擴(kuò)展。
包類型
將你的擴(kuò)展指明為 yii2-extension 類型很重要,以便安裝的時(shí)候 能被識(shí)別出是一個(gè) Yii 擴(kuò)展。
當(dāng)用戶運(yùn)行 composer install 安裝一個(gè)擴(kuò)展時(shí), vendor/yiisoft/extensions.php 文件會(huì)被自動(dòng)更新使之包含新擴(kuò)展的信息。從該文件中, Yii 應(yīng)用程序就能知道安裝了 哪些擴(kuò)展 (這些信息可通過 yii\base\Application::extensions 訪問)。
依賴
你的擴(kuò)展依賴于 Yii (理所當(dāng)然)。因此你應(yīng)當(dāng)在 composer.json 文件中列出它 (yiisoft/yii2)。如果你的擴(kuò)展還依賴其他的擴(kuò)展或者是第三方庫(kù),你也要一并列出來。 確定你也為每一個(gè)依賴的包列出了適當(dāng)?shù)陌姹炯s束條件 (比如 1.*, @stable) 。 當(dāng)你發(fā)布一個(gè)穩(wěn)定版本時(shí),你所依賴的包也應(yīng)當(dāng)使用穩(wěn)定版本。
大多數(shù) JavaScript/CSS 包是用 Bower 來管理的,而非 Composer。你可使用 Composer asset 插件 使之可以 通過 Composer 來管理這類包。如果你的擴(kuò)展依賴 Bower 軟件包,你可以如下例所示那樣簡(jiǎn)單地 在 composer.json 文件的依賴中列出它。
{ // package dependencies "require": { "bower-asset/jquery": ">=1.11.*" } }
上述代碼表明該擴(kuò)展依賴于 jquery Bower 包。一般來說,你可以在 composer.json 中用 bower-asset/PackageName 指定 Bower 包,用 npm-asset/PackageName 指定 NPM 包。 當(dāng) Compower 安裝 Bower 和 NPM 軟件包時(shí),包的內(nèi)容默認(rèn)會(huì)分別安裝到@vendor/bower/PackageName 和 @vendor/npm/Packages 下。這兩個(gè)目錄還可以分別用 @bower/PackageName 和@npm/PackageName 別名指向。
類的自動(dòng)加載
為使你的類能夠被 Yii 的類自動(dòng)加載器或者 Composer 的類自動(dòng)加載器自動(dòng)加載,你應(yīng)當(dāng)在 composer.json 中指定 autoload 條目,如下所示:
{ // .... "autoload": { "psr-4": { "yii\\imagine\\": "" } } }
你可以列出一個(gè)或者多個(gè)根命名空間和它們的文件目錄。
當(dāng)擴(kuò)展安裝到應(yīng)用中后,Yii 將為每個(gè)所列出根命名空間創(chuàng)建一個(gè) 別名 指向命名空間對(duì)應(yīng)的目錄。 例如,上述的 autoload 條目聲明將對(duì)應(yīng)于別名 @yii/imagine。
推薦的做法
擴(kuò)展意味著會(huì)被其他人使用,你在開發(fā)中通常需要額外的付出。 下面我們介紹一些通用的及推薦的做法,以創(chuàng)建高品質(zhì)的擴(kuò)展。
命名空間
為避免沖突以及使你的擴(kuò)展中的類能被自動(dòng)加載,你的類應(yīng)當(dāng)使用命名空間, 并使類的命名符合 PSR-4 standard 或者 PSR-0 standard 標(biāo)準(zhǔn)。
你的類的命名空間應(yīng)以 vendorName\extensionName 起始,其中 extensionName 和項(xiàng)目名相同,除了它沒有 yii2- 前綴外。例如,對(duì) yiisoft/yii2-imagine 擴(kuò)展 來說,我們用 yii\imagine 作為它的類的命名空間。
不要使用 yii、yii2 或者 yiisoft 作為你的 vendor 名。這些名稱已由 Yii 內(nèi)核代碼預(yù)留使用了。
類的自舉引導(dǎo)
有時(shí)候,你可能想讓你的擴(kuò)展在應(yīng)用的 自舉過程 中執(zhí)行一些代碼。 例如,你的擴(kuò)展可能想響應(yīng)應(yīng)用的 beginRequest 事件,做一些環(huán)境的設(shè)置工作。 雖然你可以指導(dǎo)擴(kuò)展的使用者顯式地將你的擴(kuò)展中的事件句柄附加(綁定)到 beginRequest 事件, 但是更好的方法是自動(dòng)完成。
為實(shí)現(xiàn)該目標(biāo),你可以創(chuàng)建一個(gè)所謂 bootstrapping class (自舉類)實(shí)現(xiàn) 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 }); } }
然后你將這個(gè)類在 composer.json 文件中列出來,如下所示,
{ // ... "extra": { "bootstrap": "myname\\mywidget\\MyBootstrapClass" } }
當(dāng)這個(gè)擴(kuò)展安裝到應(yīng)用后,Yii 將在每一個(gè)請(qǐng)求的自舉過程中 自動(dòng)實(shí)例化自舉類并調(diào)用其 yii\base\BootstrapInterface::bootstrap() 方法。
操作數(shù)據(jù)庫(kù)
你的擴(kuò)展可能要存取數(shù)據(jù)庫(kù)。不要假設(shè)使用你的擴(kuò)展的應(yīng)用總是用 Yii::$db 作為數(shù)據(jù)庫(kù)連接。你應(yīng)當(dāng)在需要訪問數(shù)據(jù)庫(kù)的類中申明一個(gè) db 屬性。 這個(gè)屬性允許你的擴(kuò)展的用戶可定制你的擴(kuò)展使用哪個(gè) DB 連接。例如, 你可以參考 yii\caching\DbCache 類看一下它是如何申明和使用 db 屬性的。
如果你的擴(kuò)展需要?jiǎng)?chuàng)建特定的數(shù)據(jù)庫(kù)表,或者修改數(shù)據(jù)庫(kù)結(jié)構(gòu),你應(yīng)當(dāng)
提供 數(shù)據(jù)遷移 來操作數(shù)據(jù)庫(kù)的結(jié)構(gòu)修改,而不是使用SQL文本文件;
盡量使遷移文件適用于不同的 DBMS;
在遷移文件中避免使用 Active Record。
使用 Assets
如果你的擴(kuò)展是掛件或者模塊類型,它有可能需要使用一些 assets 。 例如,一個(gè)模塊可能要顯示一些包含圖片,JavaScript 和 CSS 的頁(yè)面。因?yàn)閿U(kuò)展的文件 都是放在同一個(gè)目錄之下,安裝之后 Web 無法讀取,你有兩個(gè)選擇使得這些 asset 文件目錄 可以通過 Web 讀?。?/p>
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.
Articles you may be interested in:
- Detailed explanation of the use of the front-end resource package that comes with PHP's Yii framework
- Introduction to some advanced usage of caching in PHP's Yii framework
- In-depth analysis of the caching function in PHP's Yii framework
- Advanced use of View in PHP's Yii framework
- Creating and rendering views in PHP's Yii framework Detailed explanation of the method
- Tutorial on learning the Model model in PHP's Yii framework
- Detailed explanation of the Controller controller in PHP's Yii framework
- Removing components bound in PHP's Yii framework Methods for determining behavior
- Explanation of the definition and binding methods of behavior in PHP’s Yii framework
- In-depth explanation of properties in PHP’s Yii framework

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
