Readouble

Laravel 4.2 パッケージ開発

イントロダクション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].

もちろん、他の種類のパッケージも存在しています。スタンドアローンで動作するパッケージもあります。動作させるのにLaravelに限らず、どんなフレームワークも必要としません。CarbonもBehatもスタンドアローンパッケージの例です。Laravelと一緒に使用するには、composer.jsonファイルでシンプルに使用を指定します。Of course, there are different types of packages. Some packages are stand-alone, meaning they work with any framework, not just Laravel. Both Carbon and Behat are examples of stand-alone packages. Any of these packages may be used with Laravel by simply requesting them in your composer.json file.

その一方で、特にLaravelと一緒に使用されることを意図した別のパッケージも存在しています。以前のバージョンのLaravelでは、こうしたパッケージを「バンドル」と呼んでいました。この種のパッケージは、ルート、コントローラー、ビュー、設定、マイグレーションを持ち、Laravelアプリケーションを補助する目的を持っています。スタンドアローンなパッケージを開発するためには、特別な工程は必要ありませんから、このガイドでは、主にLaravelに特化した、パッケージ開発について説明していきます。On the other hand, other packages are specifically intended for use with Laravel. In previous versions of Laravel, these types of packages were called "bundles". These packages may have routes, controllers, views, configuration, and migrations specifically intended to enhance a Laravel application. As no special process is needed to develop stand-alone packages, this guide primarily covers the development of those that are Laravel specific.

Laravelのパッケージは、全てPackagistComposerにより配布されます。ですから、これらの素晴らしいPHPパッケージ配布ツールについて学ぶことは、大切です。All Laravel packages are distributed via Packagist[http://packagist.org] and Composer[http://getcomposer.org], so learning about these wonderful PHP package distribution tools is essential.

パッケージの作成Creating A Package

Laravelの新しいパッケージを作成する、一番簡単な方法は、workbench Artisanコマンドを使うことです。 最初にapp/config/workbench.phpのオプションをいくつか設定する必要があります。このファイルにはnameemailオプションがあります。それらの値は新しいパッケージに対するcomposer.jsonファイルを生成する時に使用されます。値を設定したら、ワークベンチパッケージを構築する準備が整いました!The easiest way to create a new package for use with Laravel is the workbench Artisan command. First, you will need to set a few options in the app/config/workbench.php file. In that file, you will find a name and email option. These values will be used to generate a composer.json file for your new package. Once you have supplied those values, you are ready to build a workbench package!

Workbench Artisanコマンドの実行Issuing The Workbench Artisan Command

php artisan workbench vendor/package --resources

他の製作者の同じ名前のパッケージと、あなたのものを区別するためにベンダー名は使われます。たとえば、私(Taylor Otwell)が、"Zapper"という名前で新しいパッケージを作成したら、Taylorというベンダー名、Zapperというパッケージ名を付けることができます。デフォルトでは曖昧なフレームワークパッケージが生成されます。しかしながら、resourcesコマンドによりLaravelに対しmigrationsviewsconfigなどのように特定のディレクトリーを指定し、ワークベンチへパッケージを生成するように指定できます。The vendor name is a way to distinguish your package from other packages of the same name from different authors. For example, if I (Taylor Otwell) were to create a new package named "Zapper", the vendor name could be Taylor while the package name would be Zapper. By default, the workbench will create framework agnostic packages; however, the resources command tells the workbench to generate the package with Laravel specific directories such as migrations, views, config, etc.

一度workbenchコマンドを実行すると、Laravelのインストールディレクトリーにworkbenchディレクトリーが作成されます。次に、パッケージのために作成した、サービスプロバイダー(ServiceProvider)を登録する必要があります。app/config/app.phpファイルのproviders配列に、プロバイダーを登録します。これにより、アプリケーションが開始した時点で、あなたのパッケージを読み込むように指示します。サービスプロバイダーはパッケージ名ServiceProviderという命名規則です。前記の例でしたら、Taylor\Zapper\ZapperServiceProviderproviders配列に付け加えます。Once the workbench command has been executed, your package will be available within the workbench directory of your Laravel installation. Next, you should register the ServiceProvider that was created for your package. You may register the provider by adding it to the providers array in the app/config/app.php file. This will instruct Laravel to load your package when your application starts. Service providers use a [Package]ServiceProvider naming convention. So, using the example above, you would add Taylor\Zapper\ZapperServiceProvider to the providers array.

プロバイダを登録したら、パッケージを開発する準備が整いました! しかし、実際に取り掛かる前に、パッケージ構造と開発の手順を予習しましょう。Once the provider has been registered, you are ready to start developing your package! However, before diving in, you may wish to review the sections below to get more familiar with the package structure and development workflow.

注目: もしサービスプロバイダーが見つけられない場合、アプリケーションのルートディレクトリーで、php artisan dump-autoloadコマンドを実行してください。Note: If your service provider cannot be found, run the php artisan dump-autoload command from your application's root directory

パッケージ構造Package Structure

workbenchコマンドを使えば、Laravelフレームワークの他の要素も、うまく統合したパッケージを準備してくれます。When using the workbench command, your package will be setup with conventions that allow the package to integrate well with other parts of the Laravel framework:

基本的なパッケージ構造Basic Package Directory Structure

/src
	/Vendor
		/Package
			PackageServiceProvider.php
	/config
	/lang
	/migrations
	/views
/tests
/public

この構造の特徴を説明しましょう。src/Vendor/Packageディレクトリーが、パッケージ全クラスのホームであり、ServiceProviderを含んでいます。configlangmigrationsviewsディレクトリーは名前が示す通り、対応するリソースです。「普通」のアプリケーションのように、パッケージはどんなリソースも持つことができます。Let's explore this structure further. The src/Vendor/Package directory is the home of all of your package's classes, including the ServiceProvider. The config, lang, migrations, and views directories, as you might guess, contain the corresponding resources for your package. Packages may have any of these resources, just like "regular" applications.

サービスプロバイダーService Providers

サービスプロバイダーは、パッケージのシンプルな、ブートストラップクラスです。デフォルトは、bootregisterの2つのメソッドで構成されます。このメソッド内で、何でもお好きな準備を行えます。ルートファイルをインクルードする、IoCコンテナの結合を登録する、イベントリスナーを登録するなど、何でもです。Service providers are simply bootstrap classes for packages. By default, they contain two methods: boot and register. Within these methods you may do anything you like: include a routes file, register bindings in the IoC container, attach to events, or anything else you wish to do.

registerメソッドは、サービスプロバイダーが登録された時点で、すぐに呼び出されます。その一方、bootメソッドは、リクエストがルートされる直前に、一回だけ呼び出されます。ですから、もしサービスプロバイダーの中のアクションが、既に登録されている別のサービスプロバイダーに依存していたり、他のプロバイダーに結びついたサービスをオーバーライドする場合は、bootメソッドを使用する必要があります。The register method is called immediately when the service provider is registered, while the boot command is only called right before a request is routed. So, if actions in your service provider rely on another service provider already being registered, or you are overriding services bound by another provider, you should use the boot method.

workbenchコマンドでパッケージを作成すれば、bootメソッドは以下の1アクションを含んで作成されています。When creating a package using the workbench, the boot command will already contain one action:

$this->package('vendor/package');

このメソッドは、あなたのアプリケーションに対し、ビューや設定、その他のリソースをLaravelへどうやて確実にロードすればよいのか、知らせます。ワークベンチの規則に従って準備がされているのでしたら、通常この一行を変更する必要はありません。This method allows Laravel to know how to properly load the views, configuration, and other resources for your application. In general, there should be no need for you to change this line of code, as it will setup the package using the workbench conventions.

デフォルトではパッケージを登録した後、vendor/packageの"package"部分を指定し、リソースにアクセスできます。しかしながら、packageメソッドの第2引数にしてすることで、変更可能です。例をご覧ください。By default, after registering a package, its resources will be available using the "package" half of vendor/package. However, you may pass a second argument into the package method to override this behavior. For example:

// カスタム名前空間をpackageメソッドに渡す
$this->package('vendor/package', 'custom-namespace');

// これで、custom-namespaceでパッケージのリソースにアクセスできる
$view = View::make('custom-namespace::foo');

サービスプロバイダークラスの「デフォルト設置場所」はありません。どこにでも好きな場所に置けますが、多分通常はappディレクトリーの中のProviders名前空間へ組織化し、設置することでしょう。Composerのオートロード機能が認識できる場所であればどこにでも、ファイルを設置することができます。There is not a "default location" for service provider classes. You may put them anywhere you like, perhaps organizing them in a Providers namespace within your app directory. The file may be placed anywhere, as long as Composer's auto-loading facilities[http://getcomposer.org/doc/01-basic-usage.md#autoloading] know how to load the class.

設定ファイルやビューなど、パッケージのリソースの設置場所を変更する場合は、packageメソッドの第三引数に、リソースのパスを指定してください。If you have changed the location of your package's resources, such as configuration files or views, you should pass a third argument to the package method which specifies the location of your resources:

$this->package('vendor/package', null, '/path/to/resources');

遅延プロバイダーDeferred Providers

設定やビューなどのリソースを登録しないサービスプロバイダーを書いているのでしたら、そのプロバイダーを「遅延」する選択を選ぶこともできます。遅延サービスプロバイダーは、アプリケーションのIoCコンテナにより、実際にサービスが必要になった時に、ロード、登録されます。リクエストサイクルで、プロバイダーが提供するサービスが必要ない場合、プロバイダーは一切ロードされませんIf you are writing a service provider that does not register any resources such as configuration or views, you may choose to make your provider "deferred". A deferred service provider is only loaded and registered when one of the services it provides is actually needed by the application IoC container. If none of the provider's services are needed for a given request cycle, the provider is never loaded.

サービスプロバイダーを遅延実行するには、プロバイダーのdeferプロパティーをtrueにセットしてください。To defer the execution of your service provider, set the defer property on the provider to true:

protected $defer = true;

次に、Illuminate\Support\ServiceProviderクラスのprovidesメソッドをオーバーライトし、そのプロバイダーがIoCコンテナに追加した、全結合の配列を返す必要があります。例えば、プロバイダーでpackage.servicepackage.another-serviceをIoCコンテナに登録したら、providesメソッドは、次のようになります。Next you should override the provides method from the base Illuminate\Support\ServiceProvider class and return an array of all of the bindings that your provider adds to the IoC container. For example, if your provider registers package.service and package.another-service in the IoC container, your provides method should look like this:

public function provides()
{
	return array('package.service', 'package.another-service');
}

パッケージの規約Package Conventions

パッケージの設定ファイルやビューなどのリソースを活用するため、一般的に二重のコロンの文法が使用されます。When utilizing resources from a package, such as configuration items or views, a double-colon syntax will generally be used:

パッケージからビューを読み込むLoading A View From A Package

return View::make('package::view.name');

パッケージの設定ファイルアイテムを取得するRetrieving A Package Configuration Item

return Config::get('package::group.option');

**注目:**もしパッケージがマイグレーションを含んでいるのでしたら、他のパッケージのマイグレーションと名前がかち合うのを避けるため、パッケージ名を先頭に付ける考慮をお願いします。Note: If your package contains migrations, consider prefixing the migration name with your package name to avoid potential class name conflicts with other packages.

開発ワークフローDevelopment Workflow

パッケージを開発する場合、テンプレートなどを簡単に見たり、試したりできるように、アプリケーションの内部で開発できたほうが便利です。そのため、開発を開始するときは、Laravelフレームワークを新しくインストールし、次にworkbenchコマンドでパッケージの構造を生成しましょう。When developing a package, it is useful to be able to develop within the context of an application, allowing you to easily view and experiment with your templates, etc. So, to get started, install a fresh copy of the Laravel framework, then use the workbench command to create your package structure.

workbenchコマンドでパッケージを生成した後に、workbench/[ベンダー]/[パッケージ]ディレクトリーで、git initを行い、続いてgit pustでワークベンチを直接git管理できます!この方法は、何度もcomposer updateを繰り返すことで開発が停滞すること無しに、アプリケーション上でパッケージの開発を便利に行えるようにしてくれます。After the workbench command has created your package. You may git init from the workbench/[vendor]/[package] directory and git push your package straight from the workbench! This will allow you to conveniently develop the package in an application context without being bogged down by constant composer update commands.

あなたのパッケージはworkbenchディレクトリーの中にあるのに、Composerは自動的にあなたのパッケージのファイルをロードするのは不思議に思えることでしょう。workbenchディレクトリーが存在すると、Laravelはパッケージを賢くスキャンし、アプリケーションがスタートした時点でComposerのオートロードファイルをロードします!Since your packages are in the workbench directory, you may be wondering how Composer knows to autoload your package's files. When the workbench directory exists, Laravel will intelligently scan it for packages, loading their Composer autoload files when the application starts!

もしパッケージのオートロードファイルを再生成する必要があるときは、php artisan dump-autoloadコマンドを使ってください。このコマンドはルートプロジェクトのオートロードファイルを再生成すると同時に、あなたが作成したワークベンチのものも再生成します。If you need to regenerate your package's autoload files, you may use the php artisan dump-autoload command. This command will regenerate the autoload files for your root project, as well as any workbenches you have created.

Artisanオートロードコマンドを実行するRunning The Artisan Autoload Command

php artisan dump-autoload

パッケージルーティングPackage Routing

前バージョンのLaravelではhandlesオプションで、どのURIにパッケージが対応するのかを指定していました。しかし、Laravel4ではどのURIに対してもパッケージは対応します。パッケージのルートファイルを読み込むためには、サービスプロバイダーのbootメソッドの中でシンプルにincludeしてください。In prior versions of Laravel, a handles clause was used to specify which URIs a package could respond to. However, in Laravel 4, a package may respond to any URI. To load a routes file for your package, simply include it from within your service provider's boot method.

サービスプロバイダーからルート定義ファイルインクルードするIncluding A Routes File From A Service Provider

public function boot()
{
	$this->package('vendor/package');

	include __DIR__.'/../../routes.php';
}

**注意:**パッケージでコントローラーを使用している場合、ファイルをロードできるように、composer.jsonで確実に設定してください。Note: If your package is using controllers, you will need to make sure they are properly configured in your composer.json file's auto-load section.

パッケージ設定Package Configuration

パッケージ設定ファイルにアクセスするAccessing Package Configuration Files

パッケージの中には設定ファイルを必要とするものもあります。それらのファイルは、アプリケーションの典型的な設定ファイルと同じやり方で定義しなくてはなりません。そしてサービスプロバイダーの中でリソースを登録するデフォルトの$this->packageメソッドを使用する時に、通常「二重のコロン(::)」記法を使用してアクセスします。Some packages may require configuration files. These files should be defined in the same way as typical application configuration files. And, when using the default $this->package method of registering resources in your service provider, may be accessed using the usual "double-colon" syntax:

Config::get('package::file.option');

一つだけのパッケージ設定ファイルにアクセスするAccessing Single File Package Configuration

しかし、もしパッケージに設定ファイルが一つしか必要ないのでしたら、そのファイルにconfig.phpと名付けてください。これによりに、ファイル名を指定せずとも、直接オプションにアクセスできます。However, if your package contains a single configuration file, you may simply name the file config.php. When this is done, you may access the options directly, without specifying the file name:

Config::get('package::option');

リソースの名前空間を手動で登録するRegistering A Resource Namespace Manually

場合によっては、典型的な$this->package方法から外れたビューのような、パッケージリソースを登録したい場合もあることでしょう。リソースが規約外の場所に存在している場合、これが必要になります。リソースを手動で登録するには、ViewLangConfigクラスのaddNamespaceメソッドを使用し、リソースを任意に追加できます。Sometimes, you may wish to register package resources such as views outside of the typical $this->package method. Typically, this would only be done if the resources were not in a conventional location. To register the resources manually, you may use the addNamespace method of the View, Lang, and Config classes:

View::addNamespace('package', __DIR__.'/path/to/views');

一度名前空間を登録すれば、名前空間と「二重コロン」記法で、リソースにアクセスできます。Once the namespace has been registered, you may use the namespace name and the "double colon" syntax to access the resources:

return View::make('package::view.name');

ViewLangConfigクラスのaddNamespaceメソッドの使い方は、全部同じです。The method signature for addNamespace is identical on the View, Lang, and Config classes.

カスケード式設定ファイルCascading Configuration Files

他の開発者があなたのパッケージをインストールすれば、彼らは設定オプションを上書きするでしょう。パッケージのソースコードの値を変えてしまうと、次回パッケージをComposerでアップデートした時に、変更値はオーバーライトされてしまいます。その代わりに、Artisanコマンドconfig:publishを使ってください。When other developers install your package, they may wish to override some of the configuration options. However, if they change the values in your package source code, they will be overwritten the next time Composer updates the package. Instead, the config:publish artisan command should be used:

php artisan config:publish vendor/package

このコマンドを実行すると、アプリケーションの設定ファイルは、 app/config/packages/vendor/packageにコピーされ、そこで開発者は安全に変更を加えることができます。When this command is executed, the configuration files for your application will be copied to app/config/packages/vendor/package where they can be safely modified by the developer!

**注目:**開発者は特定の環境に対するパッケージの設定ファイルをapp/config/packages/vendor/package/environmentに作成できます。Note: The developer may also create environment specific configuration files for your package by placing them in app/config/packages/vendor/package/environment.

パッケージビューPackage Views

アプリケーションの中でパッケージを使用する場合、通常パッケージのビューをカスタマイズしたいでしょう。パッケージのビューは、view:publish Artisanコマンドを使用し、app/viewsディレクトリーへエクスポートできます。If you are using a package in your application, you may occasionally wish to customize the package's views. You can easily export the package views to your own app/views directory using the view:publish Artisan command:

php artisan view:publish vendor/package

このコマンドは、パッケージのビューをapp/views/packagesディレクトリーへ移動します。そのディレクトリーが存在しない場合、コマンド実行時に作成されます。一度ビューをエクスポートすれば、それらのリンクを調整することができます!エクスポートされたビューは、自動的にパッケージ自身のビューファイルより優先されます。This command will move the package's views into the app/views/packages directory. If this directory doesn't already exist, it will be created when you run the command. Once the views have been published, you may tweak them to your liking! The exported views will automatically take precedence over the package's own view files.

パッケージマイグレーションPackage Migrations

ワークベンチパッケージに対するマイグレーションを生成するCreating Migrations For Workbench Packages

どのパッケージに対しても簡単にマイグレーションを作成し、実行できます。ワークベンチのパッケージでマイグレーションを生成するには、--benchオプションを使ってください。You may easily create and run migrations for any of your packages. To create a migration for a package in the workbench, use the --bench option:

php artisan migrate:make create_users_table --bench="vendor/package"

ワークベンチパッケージに対するマイグレーションを実行するRunning Migrations For Workbench Packages

php artisan migrate --bench="vendor/package"

インストールしたパッケージのマイグレーションを実行Running Migrations For An Installed Package

Composerを使いvendorディレクトリーにインストールし終えたパッケージのマイグレーションを実行するには、--packageオプションを使用して下さい。To run migrations for a finished package that was installed via Composer into the vendor directory, you may use the --package directive:

php artisan migrate --package="vendor/package"

パッケージアセットPackage Assets

パッケージのアセットをpublicディレクトリーに移動するMoving Package Assets To Public

パッケージによってはJavascriptやCSS、画像などのアセットを使っています。しかし、vendorworkbenchディレクトリーの中にあるアセットにリンクを張るのは不可能です。そのため、そうしたアセットをアプリケーションのpublicディレクトリーへ移動する手段が必要となります。asset:publishコマンドがこれを行います。Some packages may have assets such as JavaScript, CSS, and images. However, we are unable to link to assets in the vendor or workbench directories, so we need a way to move these assets into the public directory of our application. The asset:publish command will take care of this for you:

php artisan asset:publish

php artisan asset:publish vendor/package

パッケージがまだworkbenchにある場合は、--benchオプションを使います。If the package is still in the workbench, use the --bench directive:

php artisan asset:publish --bench="vendor/package"

このコマンドはベンダーとパッケージの名前に別にpublic/packageディレクトリーへアセットを移動します。ですから、パッケージの名前がuserscape/kudosであれば、public/packages/userscape/kudosに移動されます。パッケージのビューにアセットへのパスを安全にコードするため、このアセット発行規則を使用してください。This command will move the assets into the public/packages directory according to the vendor and package name. So, a package named userscape/kudos would have its assets moved to public/packages/userscape/kudos. Using this asset publishing convention allows you to safely code asset paths in your package's views.

パッケージ公開Publishing Packages

パッケージの公開準備が整ったら、Packagistリポジトリーへ送ってください。もしパッケージがLaravel専用なら、laravelタグをパッケージのcomposer.jsonファイルに追加することを考慮してください。When your package is ready to publish, you should submit the package to the Packagist[http://packagist.org] repository. If the package is specific to Laravel, consider adding a laravel tag to your package's composer.json file.

また、composer.jsonファイルであなたのパッケージが要求されるとき、開発者は安定バージョンを頼ることができますので、タグは親切で役に立ちます。もし、安定バージョンの用意が整っていなければ、コンポーサーのディレクティブでbranch-aliasを使用することを考えてください。Also, it is courteous and helpful to tag your releases so that developers can depend on stable versions when requesting your package in their composer.json files. If a stable version is not ready, consider using the branch-alias Composer directive.

一度パッケージを公開し終えたら、workbenchで生成されたアプリケーション構造の中で、自由に開発を続けることができます。これはパッケージ公開後も開発をやりやすく続けるための素晴らしい方法です。Once your package has been published, feel free to continue developing it within the application context created by workbench. This is a great way to continue to conveniently develop the package even after it has been published.

いくつかの組織は自分たちの開発者のパッケージのため、プライベートリポジトリーをホストすることを選んでいます。もし、これに興味をお持ちであれば、Composerチームにより提供されているSatisプロジェクトをご覧ください。Some organizations choose to host their own private repository of packages for their own developers. If you are interested in doing this, review the documentation for the Satis[http://github.com/composer/satis] project provided by the Composer team.

章選択

Artisan CLI

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作