翻译进度
8
分块数量
2
参与人数

扩展包开发

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。


包开发(Package Development)

介绍

包(Packages)是向 Laravel 添加功能的主要方式。包可以是任意功能,例如处理日期的优秀包 Carbon,或者允许你将文件与 Eloquent 模型关联的包,如 Spatie 的 Laravel Media Library

包有不同类型。有些包是独立的(stand-alone),意味着它们可以在任何 PHP 框架中使用。Carbon 和 Pest 就是独立包的例子。你可以通过在 composer.json 文件中引入它们,在 Laravel 中使用这些独立包。

另一方面,也有一些包是专为 Laravel 使用而设计的。这类包可能包含路由、控制器、视图和专门用于增强 Laravel 应用的配置。本指南主要覆盖这些专为 Laravel 开发的包。

关于 Facades 的说明(A Note on Facades)

在编写 Laravel 应用时,使用契约(contracts)或 Facades 一般差别不大,因为两者在测试可行性上基本相当。然而,在编写包时,你的包通常无法直接访问 Laravel 的所有测试辅助工具。如果你希望在编写包的测试时,就像包已经安装在典型的 Laravel 应用中一样,可以使用 Orchestral Testbench 包。

无与伦比 翻译于 5天前

包自动发现(Package Discovery)

在 Laravel 应用中,bootstrap/providers.php 文件用于列出需要加载的服务提供者(Service Providers)。通常情况下,用户需要手动将你的服务提供者添加到这个列表中,但你可以通过在你的包的 composer.json 文件中配置 extra 部分,实现 自动发现,让 Laravel 安装包时自动注册服务提供者和 Facade,从而大大简化安装流程。

例如,你可以在 composer.json 中这样配置:

"extra": {
    "laravel": {
        "providers": [
            "Barryvdh\\Debugbar\\ServiceProvider"
        ],
        "aliases": {
            "Debugbar": "Barryvdh\\Debugbar\\Facade"
        }
    }
},

一旦你的包配置了自动发现,当它被安装时,Laravel 会自动注册其服务提供者和 facade,从而为你的包的用户创建一个便利的安装体验。

选择退出包自动发现

如果你是包的使用者,并且希望禁用某个包的自动发现,你可以在你应用的 composer.json 文件的 extra 部分列出该包的名称:

"extra": {
    "laravel": {
        "dont-discover": [
            "barryvdh/laravel-debugbar"
        ]
    }
},

你也可以使用 * 字符在应用的 dont-discover 指令中禁用所有包的自动发现:

"extra": {
    "laravel": {
        "dont-discover": [
            "*"
        ]
    }
},

服务提供者

服务提供者 是你的包与 Laravel 之间的连接点。服务提供者负责将内容绑定到 Laravel 的 服务容器 中,并告诉 Laravel 从哪里加载包资源,例如视图、配置和语言文件。

服务提供者继承自 Illuminate\Support\ServiceProvider 类,并包含两个方法:registerboot。基础的 ServiceProvider 类位于 illuminate/support Composer 包中,你应该将其添加到你自己包的依赖中。想了解更多关于服务提供者的结构和用途,请查看 官方文档

无与伦比 翻译于 5天前

资源

配置

通常情况下,你需要将包的配置文件发布到应用程序的 config 目录下。这将允许在使用包时覆盖扩展包中的默认配置选项。要允许发布配置文件,需要在服务提供者的 boot 方法中调用 publishes 方法:

/**
 * 引导包服务
 */
public function boot(): void
{
    $this->publishes([
        __DIR__.'/../config/courier.php' => config_path('courier.php'),
    ]);
}

现在,当包用户执行 Laravel 的 vendor:publish 命令时,配置文件将被复制到指定的发布位置。当配置发布后,它的值可以像其他的配置文件一样被访问:

$value = config('courier.option');

警告
你不应该在你的配置文件中定义闭包。当用户执行 config:cache Artisan 命令时,它们不能被正确序列化。

默认的包配置

你也可以将你自己的包的配置文件与应用程序的发布副本合并。这将允许你的用户在配置文件的发布副本中只定义他们真正想要覆盖的选项。要合并配置文件的值,请在你的服务提供者的 register 方法中使用 mergeConfigFrom 方法。

mergeConfigFrom 方法的第一个参数是你的包的配置文件的路径,第二个参数是应用程序的配置文件副本的名称:

/**
 * 注册应用服务
 */
public function register(): void
{
    $this->mergeConfigFrom(
        __DIR__.'/../config/courier.php', 'courier'
    );
}

警告
这个方法只合并了配置数组的第一层。如果你的用户部分地定义了一个多维的配置数组,缺少的选项将不会被合并。

dkp 翻译于 1个月前

路由(Routes)

如果你的包中包含路由文件,可以使用 loadRoutesFrom 方法加载它们。该方法会自动检测应用的路由是否已经缓存,如果已经缓存,则不会重复加载路由文件:

/**
 * 启动包相关服务
 */
public function boot(): void
{
    $this->loadRoutesFrom(__DIR__.'/../routes/web.php');
}

数据迁移(Migrations)

如果你的包包含 数据库迁移,可以使用 publishesMigrations 方法告诉 Laravel 哪个目录或文件包含迁移。当 Laravel 发布迁移文件时,会自动更新文件名中的时间戳为当前时间:

/**
 * 启动包相关服务
 */
public function boot(): void
{
    $this->publishesMigrations([
        __DIR__.'/../database/migrations' => database_path('migrations'),
    ]);
}

语言文件(Language Files)

如果你的包包含 语言文件,可以使用 loadTranslationsFrom 方法告诉 Laravel 如何加载它们。例如,如果你的包名为 courier,可以在服务提供者的 boot 方法中添加:

/**
 * 启动包相关服务
 */
public function boot(): void
{
    $this->loadTranslationsFrom(__DIR__.'/../lang', 'courier');
}

在包中使用语言行时,遵循 package::file.line 的语法。例如,要加载 courier 包的 messages 文件中的 welcome 行:

echo trans('courier::messages.welcome');

如果你的包使用 JSON 格式的翻译文件,可以使用 loadJsonTranslationsFrom 方法注册:

/**
 * 启动包相关服务
 */
public function boot(): void
{
    $this->loadJsonTranslationsFrom(__DIR__.'/../lang');
}

这样 Laravel 就会自动加载你的包中的 JSON 翻译文件,方便国际化使用

无与伦比 翻译于 5天前

Publishing Language Files

If you would like to publish your package's language files to the application's lang/vendor directory, you may use the service provider's publishes method. The publishes method accepts an array of package paths and their desired publish locations. For example, to publish the language files for the courier package, you may do the following:

/**
 * Bootstrap any package services.
 */
public function boot(): void
{
    $this->loadTranslationsFrom(__DIR__.'/../lang', 'courier');

    $this->publishes([
        __DIR__.'/../lang' => $this->app->langPath('vendor/courier'),
    ]);
}

Now, when users of your package execute Laravel's vendor:publish Artisan command, your package's language files will be published to the specified publish location.

Views

To register your package's views with Laravel, you need to tell Laravel where the views are located. You may do this using the service provider's loadViewsFrom method. The loadViewsFrom method accepts two arguments: the path to your view templates and your package's name. For example, if your package's name is courier, you would add the following to your service provider's boot method:

/**
 * Bootstrap any package services.
 */
public function boot(): void
{
    $this->loadViewsFrom(__DIR__.'/../resources/views', 'courier');
}

Package views are referenced using the package::view syntax convention. So, once your view path is registered in a service provider, you may load the dashboard view from the courier package like so:

Route::get('/dashboard', function () {
    return view('courier::dashboard');
});

Overriding Package Views

When you use the loadViewsFrom method, Laravel actually registers two locations for your views: the application's resources/views/vendor directory and the directory you specify. So, using the courier package as an example, Laravel will first check if a custom version of the view has been placed in the resources/views/vendor/courier directory by the developer. Then, if the view has not been customized, Laravel will search the package view directory you specified in your call to loadViewsFrom. This makes it easy for package users to customize / override your package's views.

Publishing Views

If you would like to make your views available for publishing to the application's resources/views/vendor directory, you may use the service provider's publishes method. The publishes method accepts an array of package view paths and their desired publish locations:

/**
 * Bootstrap the package services.
 */
public function boot(): void
{
    $this->loadViewsFrom(__DIR__.'/../resources/views', 'courier');

    $this->publishes([
        __DIR__.'/../resources/views' => resource_path('views/vendor/courier'),
    ]);
}

Now, when users of your package execute Laravel's vendor:publish Artisan command, your package's views will be copied to the specified publish location.

View Components

If you are building a package that utilizes Blade components or placing components in non-conventional directories, you will need to manually register your component class and its HTML tag alias so that Laravel knows where to find the component. You should typically register your components in the boot method of your package's service provider:

use Illuminate\Support\Facades\Blade;
use VendorPackage\View\Components\AlertComponent;

/**
 * Bootstrap your package's services.
 */
public function boot(): void
{
    Blade::component('package-alert', AlertComponent::class);
}

Once your component has been registered, it may be rendered using its tag alias:

<x-package-alert/>

Autoloading Package Components

Alternatively, you may use the componentNamespace method to autoload component classes by convention. For example, a Nightshade package might have Calendar and ColorPicker components that reside within the Nightshade\Views\Components namespace:

use Illuminate\Support\Facades\Blade;

/**
 * Bootstrap your package's services.
 */
public function boot(): void
{
    Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade');
}

This will allow the usage of package components by their vendor namespace using the package-name:: syntax:

<x-nightshade::calendar />
<x-nightshade::color-picker />

Blade will automatically detect the class that's linked to this component by pascal-casing the component name. Subdirectories are also supported using "dot" notation.

Anonymous Components

If your package contains anonymous components, they must be placed within a components directory of your package's "views" directory (as specified by the loadViewsFrom method). Then, you may render them by prefixing the component name with the package's view namespace:

<x-courier::alert />

"About" Artisan Command

Laravel's built-in about Artisan command provides a synopsis of the application's environment and configuration. Packages may push additional information to this command's output via the AboutCommand class. Typically, this information may be added from your package service provider's boot method:

use Illuminate\Foundation\Console\AboutCommand;

/**
 * Bootstrap any application services.
 */
public function boot(): void
{
    AboutCommand::add('My Package', fn () => ['Version' => '1.0.0']);
}

Commands

To register your package's Artisan commands with Laravel, you may use the commands method. This method expects an array of command class names. Once the commands have been registered, you may execute them using the Artisan CLI:

use Courier\Console\Commands\InstallCommand;
use Courier\Console\Commands\NetworkCommand;

/**
 * Bootstrap any package services.
 */
public function boot(): void
{
    if ($this->app->runningInConsole()) {
        $this->commands([
            InstallCommand::class,
            NetworkCommand::class,
        ]);
    }
}

Optimize Commands

Laravel's optimize command caches the application's configuration, events, routes, and views. Using the optimizes method, you may register your package's own Artisan commands that should be invoked when the optimize and optimize:clear commands are executed:

/**
 * Bootstrap any package services.
 */
public function boot(): void
{
    if ($this->app->runningInConsole()) {
        $this->optimizes(
            optimize: 'package:optimize',
            clear: 'package:clear-optimizations',
        );
    }
}

公共资源

你的包可能有如 JavaScript、CSS 和图像之类的前端资源。要将这些资源发布到应用程序的 public 目录,请使用服务提供者的 publishes 方法。在此示例中,我们还将添加一个 public 资源组标签,该标签可以用于轻松发布相关资源组:

/**
 * 引导任何包服务
 */
public function boot(): void
{
    $this->publishes([
        __DIR__.'/../public' => public_path('vendor/courier'),
    ], 'public');
}

现在,当你的包用户运行 vendor:publish 命令时,你的资源将被复制到指定的发布位置。由于用户通常需要每次更新包时覆盖资源,你可以使用 --force 标志:

php artisan vendor:publish --tag=public --force

发布文件组

你可能想要分别发布包资源和资源组。例如,你可能希望允许用户发布包的配置文件而不强迫发布包的资源。当从包的服务提供者调用 publishes 方法时,你可以通过「tagging」它们来实现这一点。例如,让我们在包服务提供者的 boot 方法中使用标签为 courier 包定义两个发布组(courier-configcourier-migrations):

/**
 * 引导包服务
 */
public function boot(): void
{
    $this->publishes([
        __DIR__.'/../config/package.php' => config_path('package.php')
    ], 'courier-config');

    $this->publishesMigrations([
        __DIR__.'/../database/migrations/' => database_path('migrations')
    ], 'courier-migrations');
}

现在,你的用户可以通过在执行 vendor:publish 命令时引用其标签,分别发布这些组:

php artisan vendor:publish --tag=courier-config

你的用户还可以使用 --provider 标志发布包服务提供商定义的所有可发布文件:

php artisan vendor:publish --provider="Your\Package\ServiceProvider"
dkp 翻译于 1个月前

本文章首发在 LearnKu.com 网站上。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
贡献者:2
讨论数量: 0
发起讨论 只看当前版本


暂无话题~