イントロダクションIntroduction
パッケージは、Laravelに機能を追加するための主要な方法です。パッケージは、Carbonのような日付を処理するための優れた方法から、SpatieのLaravel Media LibraryのようなEloquentモデルにファイルを関連付けることができるパッケージまであります。Packages are the primary way of adding functionality to Laravel. Packages might be anything from a great way to work with dates like Carbon[https://github.com/briannesbitt/Carbon] or a package that allows you to associate files with Eloquent models like Spatie's Laravel Media Library[https://github.com/spatie/laravel-medialibrary].
パッケージにはさまざまな種類があります。スタンドアロン型のパッケージもあり、どのPHPフレームワークでも動作します。CarbonやPestはスタンドアロンパッケージの例です。これらのパッケージは、composer.json
ファイルで要求すれば、Laravelで使用できます。There are different types of
packages. Some packages are stand-alone, meaning
they work with any PHP framework. Carbon and Pest
are examples of stand-alone packages. Any of these
packages may be used with Laravel by requiring them
in your composer.json
file.
逆にLaravelと一緒に使用することを意図したパッケージもあります。こうしたパッケージはLaravelアプリケーションを高めること特に意図したルート、コントローラ、ビュー、設定を持つでしょう。このガイドでは、Laravelに特化したパッケージの開発を主に説明します。On the other hand, other packages are specifically intended for use with Laravel. These packages may have routes, controllers, views, and configuration specifically intended to enhance a Laravel application. This guide primarily covers the development of those packages that are Laravel specific.
ファサード使用の注意A Note on Facades
Laravelアプリケーションを作成する場合、コントラクトとファサードのどちらを使用しても、どちらも基本的に同じレベルのテスト容易性を提供するため、通常は問題になりません。ただし、パッケージを作成する場合、通常、パッケージはLaravelのすべてのテストヘルパにアクセスできるわけではありません。パッケージが一般的なLaravelアプリケーション内にインストールされているかのようにパッケージテストを記述できるようにしたい場合は、Orchestral Testbenchパッケージを使用できます。When writing a Laravel application, it generally does not matter if you use contracts or facades since both provide essentially equal levels of testability. However, when writing packages, your package will not typically have access to all of Laravel's testing helpers. If you would like to be able to write your package tests as if the package were installed inside a typical Laravel application, you may use the Orchestral Testbench[https://github.com/orchestral/testbench] package.
パッケージディスカバリーPackage Discovery
Laravelアプリケーションのbootstrap/providers.php
ファイルには、Laravelがロードするべきサービスプロバイダのリストが含まれています。しかし、ユーザーが自分でサービスプロバイダをリストへ追加する代わりに、パッケージのcomposer.json
ファイルのextra
セクションプロバイダを定義して、Laravelが自動的にロードすることもできます。サービスプロバイダに加え、登録したいファサードをリストすることもできます。A Laravel application's
bootstrap/providers.php
file contains
the list of service providers that should be loaded
by Laravel. However, instead of requiring users to
manually add your service provider to the list, you
may define the provider in the extra
section of your package's composer.json
file so that it is automatically loaded by Laravel.
In addition to service providers, you may also list
any facades[/docs/{{version}}/facades] you
would like to be registered:
"extra": {
"laravel": {
"providers": [
"Barryvdh\\Debugbar\\ServiceProvider"
],
"aliases": {
"Debugbar": "Barryvdh\\Debugbar\\Facade"
}
}
},
ディスカバリー用にパッケージを設定したら、Laravelはサービスプロバイダとファサードをインストール時に自動的に登録します。皆さんのパッケージユーザーに、便利なインストール体験をもたらします。Once your package has been configured for discovery, Laravel will automatically register its service providers and facades when it is installed, creating a convenient installation experience for your package's users.
パッケージディスカバリーの不使用Opting Out of Package Discovery
パッケージを利用する場合に、パッケージディスカバリーを使用したくない場合は、アプリケーションのcomposer.json
ファイルのextra
セクションに、使用しないパッケージをリストしてください。If you are the consumer of a
package and would like to disable package discovery
for a package, you may list the package name in the
extra
section of your application's
composer.json
file:
"extra": {
"laravel": {
"dont-discover": [
"barryvdh/laravel-debugbar"
]
}
},
全パッケージに対してディスカバリーを使用しない場合は、アプリケーションのdont-discover
ディレクティブに、*
文字を指定してください。You may disable package discovery
for all packages using the *
character
inside of your application's
dont-discover
directive:
"extra": {
"laravel": {
"dont-discover": [
"*"
]
}
},
サービスプロバイダService Providers
サービスプロバイダは、あなたのパッケージとLaravelの接続ポイントです。サービスプロバイダは、Laravelのサービスコンテナで必要なものを結合し、ビュー、設定、言語ファイルなどのパッケージリソースをロードする場所をLaravelへ知らせる役割を持っています。Service providers[/docs/{{version}}/providers] are the connection point between your package and Laravel. A service provider is responsible for binding things into Laravel's service container[/docs/{{version}}/container] and informing Laravel where to load package resources such as views, configuration, and language files.
サービスプロバイダはIlluminate\Support\ServiceProvider
クラスを拡張し、register
とboot
の2メソッドを含んでいます。ベースのServiceProvider
クラスは、illuminate/support
Composerパッケージにあります。 サービスプロバイダの構造と目的について詳細を知りたければ、ドキュメントを調べてください。A service provider extends the
Illuminate\Support\ServiceProvider
class and contains two methods:
register
and boot
. The
base ServiceProvider
class is located
in the illuminate/support
Composer
package, which you should add to your own package's
dependencies. To learn more about the structure and
purpose of service providers, check out their
documentation[/docs/{{version}}/providers].
リソースResources
設定Configuration
通常、パッケージの設定ファイルをアプリケーションのconfig
ディレクトリにリソース公開する必要があります。これにより、パッケージのユーザーはデフォルトの設定オプションを簡単に上書きできます。設定ファイルをリソース公開できるようにするには、サービスプロバイダのboot
メソッドからpublishes
メソッドを呼び出します。Typically, you will need to
publish your package's configuration file to the
application's config
directory. This
will allow users of your package to easily override
your default configuration options. To allow your
configuration files to be published, call the
publishes
method from the
boot
method of your service
provider:
/**
* 全パッケージサービスの初期起動処理
*/
public function boot(): void
{
$this->publishes([
__DIR__.'/../config/courier.php' => config_path('courier.php'),
]);
}
これで、皆さんのパッケージのユーザーが、Laravelのvendor:publish
コマンドを実行すると、特定のリソース公開場所へファイルがコピーされます。設定がリソース公開されても、他の設定ファイルと同様に値にアクセスできます。Now, when users of your package
execute Laravel's vendor:publish
command, your file will be copied to the specified
publish location. Once your configuration has been
published, its values may be accessed like any other
configuration file:
$value = config('courier.option');
Warning! 設定ファイルでクロージャを定義しないでください。ユーザーが
config:cache
Artisanコマンドを実行すると、正しくシリアル化できません。[!WARNING]
You should not define closures in your configuration files. They can not be serialized correctly when users execute theconfig:cache
Artisan command.
デフォルトパッケージ設定Default Package Configuration
独自のパッケージ設定ファイルをアプリケーションのリソース公開コピーとマージすることもできます。これにより、ユーザーは、設定ファイルのリソース公開されたコピーで実際にオーバーライドするオプションのみを定義できます。設定ファイルの値をマージするには、サービスプロバイダのregister
メソッド内でmergeConfigFrom
メソッドを使用します。You may also merge your own
package configuration file with the application's
published copy. This will allow your users to define
only the options they actually want to override in
the published copy of the configuration file. To
merge the configuration file values, use the
mergeConfigFrom
method within your
service provider's register
method.
mergeConfigFrom
メソッドは、パッケージの設定ファイルへのパスを最初の引数に取り、アプリケーションの設定ファイルのコピーの名前を2番目の引数に取ります。The mergeConfigFrom
method accepts the path to your package's
configuration file as its first argument and the
name of the application's copy of the configuration
file as its second argument:
/**
* 全アプリケーションサービスの登録
*/
public function register(): void
{
$this->mergeConfigFrom(
__DIR__.'/../config/courier.php', 'courier'
);
}
[!WARNING]
Warning! このメソッドは設定配列の一次レベルのみマージします。パッケージのユーザーが部分的に多次元の設定配列を定義すると、マージされずに欠落するオプションが発生します。
This method only merges the first level of the configuration array. If your users partially define a multi-dimensional configuration array, the missing options will not be merged.
ルートRoutes
パッケージにルートを含めている場合は、loadRoutesFrom
メソッドでロードします。このメソッドは自動的にアプリケーションのルートがキャッシュされているかを判定し、すでにキャッシュ済みの場合はロードしません。If your package contains routes,
you may load them using the
loadRoutesFrom
method. This method will
automatically determine if the application's routes
are cached and will not load your routes file if the
routes have already been cached:
/**
* 全パッケージサービスの初期起動処理
*/
public function boot(): void
{
$this->loadRoutesFrom(__DIR__.'/../routes/web.php');
}
マイグレーションMigrations
パッケージにデータベースマイグレーションが含まれている場合、publishesMigrations
メソッドを使用して、指定ディレクトリまたはファイルにマイグレーションが含まれていることをLaravelに知らせることができます。Laravelがマイグレーションをリソース公開すると、ファイル名内のタイムスタンプが自動的に更新され、現在の日時が反映されます:If your package contains
database
migrations[/docs/{{version}}/migrations],
you may use the publishesMigrations
method to inform Laravel that the given directory or
file contains migrations. When Laravel publishes the
migrations, it will automatically update the
timestamp within their filename to reflect the
current date and time:
/**
* 全パッケージサービスの初期起動処理
*/
public function boot(): void
{
$this->publishesMigrations([
__DIR__.'/../database/migrations' => database_path('migrations'),
]);
}
言語ファイルLanguage Files
パッケージに言語ファイルを用意している場合、loadTranslationsFrom
メソッドを使用して、それらをロードする方法をLaravelへ知らせてください。例えば、パッケージの名前がcourier
の場合、サービスプロバイダのboot
メソッドに以下を追加する必要があります。If your package contains
language
files[/docs/{{version}}/localization], you
may use the loadTranslationsFrom
method
to inform Laravel how to load them. For example, if
your package is named courier
, you
should add the following to your service provider's
boot
method:
/**
* 全パッケージサービスの初期起動処理
*/
public function boot(): void
{
$this->loadTranslationsFrom(__DIR__.'/../lang', 'courier');
}
パッケージの翻訳行は、package::file.line
の規約で参照します。したがって、courier
パッケージのmessages
ファイルから、welcome
は以下のように読み込みます。Package translation lines are
referenced using the package::file.line
syntax convention. So, you may load the
courier
package's welcome
line from the messages
file like
so:
echo trans('courier::messages.welcome');
loadJsonTranslationsFrom
メソッドを使うと、パッケージへJSON翻訳ファイルを登録できます。このメソッドで、パッケージのJSON翻訳ファイルがあるディレクトリパスを指定します。You can register JSON translation
files for your package using the
loadJsonTranslationsFrom
method. This
method accepts the path to the directory that
contains your package's JSON translation
files:
/**
* パッケージの全サービスの起動処理
*/
public function boot(): void
{
$this->loadJsonTranslationsFrom(__DIR__.'/../lang');
}
言語ファイルのリソース公開Publishing Language Files
パッケージの言語ファイルをアプリケーションのlang/vendor
ディレクトリへリソース公開したい場合は、サービスプロバイダのpublishes
メソッドを使用します。publishes
メソッドは、パッケージのパスと公開したい場所の配列を引数に取ります。例えば、courier
パッケージの言語ファイルを公開するには、以下のようにします。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:
/**
* 全パッケージサービスの初期起動処理
*/
public function boot(): void
{
$this->loadTranslationsFrom(__DIR__.'/../lang', 'courier');
$this->publishes([
__DIR__.'/../lang' => $this->app->langPath('vendor/courier'),
]);
}
これで、パッケージのユーザーがLaravelのvendor:publish
Artisanコマンドを実行すると、パッケージの言語ファイルが指定した公開場所にリソース公開されます。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
パッケージのビューをLaravelへ登録するには、ビューがどこにあるのかをLaravelに知らせる必要があります。そのために、サービスプロバイダのloadViewsFrom
メソッドを使用してください。loadViewsFrom
メソッドは2つの引数を取ります。ビューテンプレートへのパスと、パッケージの名前です。たとえば、パッケージ名がcourier
であれば、以下の行をサービスプロバイダのboot
メソッドに追加してください。To register your package's
views[/docs/{{version}}/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:
/**
* 全パッケージサービスの初期起動処理
*/
public function boot(): void
{
$this->loadViewsFrom(__DIR__.'/../resources/views', 'courier');
}
パッケージのビューは、package::view
記法を使い参照します。そのため、ビューのパスを登録し終えたあとで、courier
パッケージのdashboard
ビューをロードする場合は、次のようになります。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
loadViewsFrom
メソッドを使用すると、Laravelはビューの2つの場所を実際に登録します。アプリケーションのresources/views/vendor
ディレクトリと指定したディレクトリです。そのため、たとえばcourier
パッケージを使用すると、Laravelは最初にカスタムバージョンのビューが開発者によってresources/views/vendor/courier
ディレクトリに配置されているかどうかを確認します。次に、ビューがカスタマイズされていない場合、LaravelはloadViewsFrom
の呼び出しで指定したパッケージビューディレクトリを検索します。これにより、パッケージユーザーはパッケージのビューを簡単にカスタマイズ/オーバーライドできます。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
パッケージのビューをresources/views/vendor
ディレクトリでリソース公開したい場合は、サービスプロバイダのpublishes
メソッドを使ってください。publishes
メソッドはパッケージのビューパスと、リソース公開場所の配列を引数に取ります。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:
/**
* 全パッケージサービスの初期起動処理
*/
public function boot(): void
{
$this->loadViewsFrom(__DIR__.'/../resources/views', 'courier');
$this->publishes([
__DIR__.'/../resources/views' => resource_path('views/vendor/courier'),
]);
}
これで皆さんのパッケージのユーザーが、Laravelのvendor::publish
Artisanコマンドを実行すると、パッケージのビューは指定されたリソース公開場所へコピーされます。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
Bladeコンポーネントを利用するパッケージを構築する場合、またはコンポーネントを従来と異なるディレクトリへ配置する場合、コンポーネントクラスとそのHTMLタグエイリアスを手作業で登録し、Laravelがコンポーネントを見つける場所を認識できるようにする必要があります。通常、パッケージのサービスプロバイダのboot
メソッドで、コンポーネントを登録する必要があります。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;
/**
* アプリケーションの全サービスの初期起動処理
*/
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
もしくは、componentNamespace
メソッドを使用して、コンポーネントクラスを規約に従いオートロードできます。例えば、Nightshade
パッケージにCalendar
とColorPicker
コンポーネントがあり、これらがNightshade\Views\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;
/**
* アプリケーションの全サービスの初期起動処理
*/
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は、コンポーネント名をパスカルケース化し、このコンポーネントとリンクしているクラスを自動的に検出します。サブディレクトリも「ドット」記法でサポートしています。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
パッケージが無名コンポーネントを持っている場合、"views"ディレクトリ(loadViewsFrom
で指定している場所)の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[#views]).
Then, you may render them by prefixing the component
name with the package's view namespace:
<x-courier::alert />
"About" Artisanコマンド"About" Artisan Command
Laravelの組み込みabout
Artisanコマンドは、アプリケーションの環境と設定の概要を表示します。パッケージではAboutCommand
クラスを使用して、このコマンドの出力に追加情報を追加できます。一般的に、この情報はパッケージサービスプロバイダのboot
メソッドに追加します。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;
/**
* アプリケーションの全サービスの初期起動処理
*/
public function boot(): void
{
AboutCommand::add('My Package', fn () => ['Version' => '1.0.0']);
}
コマンドCommands
パッケージのArtisanコマンドをLaravelへ登録するには、commands
メソッドを使います。このメソッドは、コマンドクラス名の配列を引数に取ります。コマンドを登録したら、Artisan CLIを使い、実行できます。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[/docs/{{version}}/artisan]:
use Courier\Console\Commands\InstallCommand;
use Courier\Console\Commands\NetworkCommand;
/**
* 全パッケージサービスの初期起動処理
*/
public function boot(): void
{
if ($this->app->runningInConsole()) {
$this->commands([
InstallCommand::class,
NetworkCommand::class,
]);
}
}
リソース公開アセットPublic Assets
パッケージには、JavaScript、CSS、画像などのアセットが含まれている場合があります。これらのアセットをアプリケーションのpublic
ディレクトリにリソース公開するには、サービスプロバイダのpublishes
メソッドを使用します。この例では、関連するアセットのグループを簡単にリソース公開するために使用できるpublic
アセットグループタグも追加します。Your package may have assets such
as JavaScript, CSS, and images. To publish these
assets to the application's public
directory, use the service provider's
publishes
method. In this example, we
will also add a public
asset group tag,
which may be used to easily publish groups of
related assets:
/**
* 全パッケージサービスの初期起動処理
*/
public function boot(): void
{
$this->publishes([
__DIR__.'/../public' => public_path('vendor/courier'),
], 'public');
}
これで、パッケージのユーザーがvendor:publish
コマンドを実行すると、アセットが指定するリソース公開場所にコピーされます。通常、ユーザーはパッケージが更新されるたびにアセットを上書きする必要があるため、--force
フラグを使用できます。Now, when your package's users
execute the vendor:publish
command,
your assets will be copied to the specified publish
location. Since users will typically need to
overwrite the assets every time the package is
updated, you may use the --force
flag:
php artisan vendor:publish --tag=public --force
ファイルグループのリソース公開Publishing File Groups
パッケージアセットとリソースのグループを個別にリソース公開することを推奨します。たとえば、パッケージのアセットをリソース公開することを強制されることなく、ユーザーがパッケージの設定ファイルをリソース公開できるようにしたい場合もあるでしょう。パッケージのサービスプロバイダからpublishes
メソッドを呼び出すときに、それらに「タグ付け」することでこれを行うことができます。例として、パッケージのサービスプロバイダのboot
メソッドで、courier
パッケージの2公開グループ
(courier-config
とcourier-migrations
)をタグを使い定義してみましょう。You may want to publish groups of
package assets and resources separately. For
instance, you might want to allow your users to
publish your package's configuration files without
being forced to publish your package's assets. You
may do this by "tagging" them when calling
the publishes
method from a package's
service provider. For example, let's use tags to
define two publish groups for the
courier
package
(courier-config
and
courier-migrations
) in the
boot
method of the package's service
provider:
/**
* 全パッケージサービスの初期起動処理
*/
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
Artisanコマンドを使用するときにタグ名を指定することで、グループを別々にリソース公開できます。Now your users may publish these
groups separately by referencing their tag when
executing the vendor:publish
command:
php artisan vendor:publish --tag=courier-config