イントロダクションIntroduction
パッケージはLaravelに機能を追加する一番重要な方法です。パッケージとして何でも動作させることができます。たとえば日付ライブラリーであるCarbonや、振る舞い駆動開発(BDD)テストフレームワークのBehatなどです。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 an entire BDD testing framework like Behat[https://github.com/Behat/Behat].
パッケージには、色々な種類が存在しています。スタンドアローンで動作するパッケージがあります。つまり、どんなPHPフレームワークでも動作します。CarbonもBehatもスタンドアローンパッケージの例です。Laravelと一緒に使用するにはcomposer.json
ファイルで使用を指定します。There are different types of
packages. Some packages are stand-alone, meaning
they work with any PHP framework. Carbon and Behat
are examples of stand-alone packages. Any of these
packages may be used with Laravel by requesting 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 they existed inside a typical Laravel application, you may use the Orchestral Testbench[https://github.com/orchestral/testbench] package.
パッケージディスカバリーPackage Discovery
Laravelアプリケーションのconfig/app.php
設定ファイルには、Laravelがロードすべきサービスプロバイダのリストが、providers
オプションで定義されています。誰かが皆さんのパッケージをインストールしたら、皆さんのサービスプロバイダをこのリストに含めてもらいたいと思うことでしょう。このリストへユーザー自身がサービスプロバイダを追加することを要求する代わりに、皆さんのパッケージのcomposer.json
ファイルのextra
セクションで、プロバイダを定義してください。登録してもらいたいファサードもリストできます。In a Laravel application's
config/app.php
configuration file, the
providers
option defines a list of
service providers that should be loaded by Laravel.
When someone installs your package, you will
typically want your service provider to be included
in this list. 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. 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 points 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 localization 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 own 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:
/**
* 全アプリケーションサービスの初期起動
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/path/to/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');
Note:
設定ファイル中でクロージャを定義してはいけません。パッケージ使用者がconfig:cache
Artisanコマンドを使用している場合に、正しくシリアライズできません。{note} 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. To merge
the configurations, use the
mergeConfigFrom
method within your
service provider's register
method:
/**
* 全アプリケーションサービスの登録
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/path/to/config/courier.php', 'courier'
);
}
Note: {note} 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:
/**
* 全アプリケーションサービスの初期起動
*
* @return void
*/
public function boot()
{
$this->loadRoutesFrom(__DIR__.'/routes.php');
}
マイグレーションMigrations
もしパッケージがデータベースマイグレーションを含んでいる場合、loadMigrationsFrom
メソッドを使用し、Laravelへどのようにロードするのかを知らせます。loadMigrationsFrom
メソッドは引数を一つ取り、パッケージのマイグレーションのパスです。If your package contains
database
migrations[/docs/{{version}}/migrations],
you may use the loadMigrationsFrom
method to inform Laravel how to load them. The
loadMigrationsFrom
method accepts the
path to your package's migrations as its only
argument:
/**
* 全アプリケーションサービスの初期起動
*
* @return void
*/
public function boot()
{
$this->loadMigrationsFrom(__DIR__.'/path/to/migrations');
}
パッケージのマイグレーションが登録されると、php artisan
migrate
コマンド実行時に、自動的にパッケージのマイグレーションも行われます。アプリケーションのdatabase/migrations
ディレクトリへ公開する必要はありません。Once your package's migrations
have been registered, they will automatically be run
when the php artisan migrate
command is
executed. You do not need to export them to the
application's main database/migrations
directory.
ファクトリFactories
パッケージにデータベースファクトリを含める場合は、Laravelにどのようにロードするかを教えるために、loadFactoriesFrom
メソッドを使用してください。loadFactoriesFrom
メソッドの唯一の引数は、パッケージのファクトリへのパスです。If your package contains
database
factories[/docs/{{version}}/database-testing#writing-factories],
you may use the loadFactoriesFrom
method to inform Laravel how to load them. The
loadFactoriesFrom
method accepts the
path to your package's factories as its only
argument:
/**
* 全アプリケーションサービスの初期起動
*
* @return void
*/
public function boot()
{
$this->loadFactoriesFrom(__DIR__.'/path/to/factories');
}
パッケージのファクトリを登録したら、アプリケーションで使用できます。Once your package's factories have been registered, you can use them in your application:
factory(Package\Namespace\Model::class)->create();
言語ファイルTranslations
パッケージが言語ファイルを含む場合、loadTranslationsFrom
メソッドを使用し、Laravelへどのようにロードするのかを伝えてください。たとえば、パッケージの名前がcourier
の場合、以下のコードをサービスプロバイダのboot
メソッドに追加します。If your package contains
translation
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:
/**
* 全アプリケーションサービスの初期起動
*
* @return void
*/
public function boot()
{
$this->loadTranslationsFrom(__DIR__.'/path/to/translations', 'courier');
}
パッケージの翻訳は、package::file.line
規約を使い参照します。ですから、courier
パッケージのmessages
ファイル中の、welcome
行をロードするには、次のようになります。Package translations 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');
翻訳の公開Publishing Translations
パッケージの翻訳をアプリケーションのresources/lang/vendor
ディレクトリへ公開したい場合は、サービスプロバイダのpublishes
メソッドを使用します。publishes
メソッドはパッケージパスと公開したい場所の配列を引数に取ります。たとえば、courier
パッケージの言語ファイルを公開する場合は、次のようになります。If you would like to publish your
package's translations to the application's
resources/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 translation files for
the courier
package, you may do the
following:
/**
* 全アプリケーションサービスの初期起動
*
* @return void
*/
public function boot()
{
$this->loadTranslationsFrom(__DIR__.'/path/to/translations', 'courier');
$this->publishes([
__DIR__.'/path/to/translations' => resource_path('lang/vendor/courier'),
]);
}
これで、皆さんのパッケージのユーザーが、Laravelのvendor:publish
Artisanコマンドを実行すると、パッケージの翻訳は指定された公開場所で公開されます。Now, when users of your package
execute Laravel's vendor:publish
Artisan command, your package's translations 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:
/**
* 全アプリケーションサービスの初期起動
*
* @return void
*/
public function boot()
{
$this->loadViewsFrom(__DIR__.'/path/to/views', 'courier');
}
パッケージのビューは、package::view
記法を使い参照します。そのため、ビューのパスを登録し終えたあとで、courier
パッケージのadmin
ビューをロードする場合は、次のようになります。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
admin
view from the
courier
package like so:
Route::get('admin', function () {
return view('courier::admin');
});
パッケージビューのオーバーライドOverriding Package Views
loadViewsFrom
メソッドを使用する場合、Laravelはビューの2つの場所を実際には登録します。一つはアプリケーションのresources/views/vendor
ディレクトリで、もう一つは皆さんが指定したディレクトリです。では、courier
の例を使って確認しましょう。Laravelは最初にresources/views/vendor/courier
の中に、カスタムバージョンのビューが開発者により用意されていないかチェックします。カスタムビューが用意されていなければ、次に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
example, Laravel will first
check if a custom version of the view has been
provided by the developer in
resources/views/vendor/courier
. 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:
/**
* 全アプリケーションサービスの初期起動
*
* @return void
*/
public function boot()
{
$this->loadViewsFrom(__DIR__.'/path/to/views', 'courier');
$this->publishes([
__DIR__.'/path/to/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.
コマンド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]:
/**
* アプリケーションサービスの初期処理
*
* @return void
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->commands([
FooCommand::class,
BarCommand::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 publish groups of related
assets:
/**
* 全アプリケーションサービスの初期起動
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/path/to/assets' => 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 you 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
メソッドで、2つの公開グループを定義してみましょう。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 in the boot
method of a package service provider:
/**
* 全アプリケーションサービスの初期起動
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/../config/package.php' => config_path('package.php')
], 'config');
$this->publishes([
__DIR__.'/../database/migrations/' => database_path('migrations')
], '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=config