# Services

- [Introduction](#introduction)
- [Building your services](#building-your-services)
    - [Depending on other services](#depending-on-other-services)
    - [Interfaces and concrete types](#interfaces-and-concrete-types)
    - [Reusable HTTP clients](#reusable-http-clients)
- [Using services](#using-services)
    - [In handlers and middleware](#in-handlers-and-middleware)
    - [In jobs, commands, and domain packages](#in-jobs-commands-and-domain-packages)
- [Organizing services as your application grows](#organizing-services-as-your-application-grows)
    - [What belongs on `Services`](#what-belongs-on-services)
    - [Avoiding import cycles](#avoiding-import-cycles)
- [Shared state and concurrency](#shared-state-and-concurrency)
- [Testing with services](#testing-with-services)

<a name="introduction"></a>

## Introduction


多くのアプリケーションは、決済プロバイダのクライアント、検索クライアント、ジオコーダーなどを起動時に一度構築し、複数のハンドラーやジョブで共有します。毎リクエストで作ると接続を浪費し環境の読み取りを繰り返しますが、全依存をルート、ジョブ構造体、ヘルパへ逐一渡すとシグネチャが煩雑になります。


`services/services.go` の `services` パッケージで解決できます。共有依存を格納する `Services`、起動時に環境から一度構築する `New`、リクエストや [context](/ja/go/docs/context) から取り出す `From` を定義します。

```go
// services/services.go
package services

import (
	"context"

	laravel "go.laravel.com"
	"go.laravel.com/config"
)

type Services struct{}

func New(env *config.Env, app *laravel.App) Services {
	return Services{}
}

func From(ctx context.Context) *Services {
	return laravel.ServicesOf[*Services](ctx)
}
```


`bootstrap/app.go` の `Services: laravel.BuildServices(services.New)` がコンストラクタを登録します。Laravel はデータベース、キャッシュ、キュー、トレーシングなどを構築後、`services.New` を一度呼び、`*Services` をアプリケーションに付けます。パッケージのグローバルではないため、各テストが独立した `Services` を構築し、並行テストに影響せずフィールドを交換できます。


データベース、キャッシュ、メーラー、ストレージ、キューは `db.Table` や `mail.To` などのパッケージからコンテキストに接続済みです。`services.Services` に追加するのは独自のクライアント、SDK、設定だけです。

<a name="building-your-services"></a>

## Building your services


Stripe などと通信する場合は `billing` などの独立したパッケージにクライアントを作り、`services/services.go` で接続します。次の `billing` は決済プロバイダを `Client` 型で包みます。

```go
// billing/client.go
package billing

import (
	"context"
	"errors"
	"net/url"
	"strconv"

	"go.laravel.com/httpclient"
)

type Client struct {
	key      string
	currency string
}

func NewClient(key, currency string) *Client {
	return &Client{key: key, currency: currency}
}

func (c *Client) Charge(ctx context.Context, cents int64) error {
	if c.key == "" {
		return errors.New("billing: STRIPE_KEY is not set")
	}

	_, err := httpclient.Token(c.key).
		Form(url.Values{
			"amount":   {strconv.FormatInt(cents, 10)},
			"currency": {c.currency},
		}).
		EnsureSuccessful().
		Post(ctx, "https://api.stripe.com/v1/payment_intents")

	return err
}
```


次に `Services` に `Billing` を加え、`services.New` で構築します。Laravel は自身と同じ `*config.Env` を渡すため、ローカルでは `.env`、本番ではプロセス環境から変数を読みます。

```go
// services/services.go
package services

import (
	"context"

	laravel "go.laravel.com"
	"go.laravel.com/config"

	"app/billing"
)

type Services struct {
	Billing *billing.Client
}

func New(env *config.Env, app *laravel.App) Services {
	return Services{
		Billing: billing.NewClient(
			env.String("STRIPE_KEY", ""),
			env.String("BILLING_CURRENCY", "usd"),
		),
	}
}

func From(ctx context.Context) *Services {
	return laravel.ServicesOf[*Services](ctx)
}
```


`env.Int` に数値以外が入るなど無効な値があると、起動を止めて問題を表示します。`env` の型付き読み取りは [your own settings](/ja/go/docs/configuration#your-own-settings) を参照してください。

> [!NOTE]
> `STRIPE_KEY` などは `services.New` で空のフォールバックを与え、キーなしで実際にクライアントを呼んだ時点でエラーにします。全コンソールコマンドがサービスを構築するため、`services.New` で失敗すると、複製直後で `.env` のない状態の `laravel key:generate` なども実行できなくなります。

<a name="depending-on-other-services"></a>

### Depending on other services


別サービスに依存する場合は `services.New` で先に依存先を構築して次のコンストラクタへ渡します。たとえば `billing.Client` が決済前の税計算に `tax.Calculator` を必要とするなら、`taxCalculator` を先に作り `billing.NewClient` へ渡します。

```go
// services/services.go
func New(env *config.Env, app *laravel.App) Services {
	taxCalculator := tax.NewCalculator(env.String("TAX_API_KEY", ""))

	billingClient := billing.NewClient(
		env.String("STRIPE_KEY", ""),
		env.String("BILLING_CURRENCY", "usd"),
		taxCalculator,
	)

	return Services{
		Tax:     taxCalculator,
		Billing: billingClient,
	}
}
```


明示的に渡すことで依存グラフが一箇所にまとまり、実行前に Go コンパイラーが引数不足を検出できます。

<a name="interfaces-and-concrete-types"></a>

### Interfaces and concrete types


最初は `Services` に `*billing.Client` などの具体的なポインター型を使います。実装が複数ある場合や、HTTP テストサーバーなしで軽量なメモリ内フェイクに替えたい場合はインターフェイスを使います。


たとえば `geo` は Mapbox の実装と小さな `Geocoder` インターフェイスを定義できます。

```go
// geo/geocoder.go
package geo

import "context"

type Coordinates struct {
	Latitude  float64
	Longitude float64
}

type Geocoder interface {
	Locate(ctx context.Context, address string) (Coordinates, error)
}
```


`services/services.go` の型を `geo.Geocoder` とし、`New` で本番用実装を接続します。

```go
// services/services.go
type Services struct {
	Billing  *billing.Client
	Geocoder geo.Geocoder
}

func New(env *config.Env, app *laravel.App) Services {
	return Services{
		Billing: billing.NewClient(
			env.String("STRIPE_KEY", ""),
			env.String("BILLING_CURRENCY", "usd"),
		),
		Geocoder: geo.NewMapbox(env.String("MAPBOX_TOKEN", "")),
	}
}
```

<a name="reusable-http-clients"></a>

### Reusable HTTP clients


ベース URL、Bearer トークン、タイムアウトだけが必要なら独自のラッパーパッケージは不要です。再利用する `*httpclient.Client` テンプレートを `Services` に直接保存します。

```go
// services/services.go
type Services struct {
	GitHub *httpclient.Client
}

func New(env *config.Env, app *laravel.App) Services {
	return Services{
		GitHub: httpclient.BaseURL("https://api.github.com").
			Token(env.String("GITHUB_TOKEN", "")).
			AcceptJSON().
			EnsureSuccessful(),
	}
}
```


`httpclient.BaseURL` から始めると、`Get` や `Post` のコンテキストにあるアプリケーション経由でリクエストするため、テストでも `httpclienttest` が捕捉できます。詳細は [base URLs and reusable clients](/ja/go/docs/http-client#base-urls-and-reusable-clients) を参照してください。

<a name="using-services"></a>

## Using services

<a name="in-handlers-and-middleware"></a>

### In handlers and middleware


ハンドラーや [middleware](/ja/go/docs/middleware) で `r` を `services.From` に渡し、サービスを取得します。

```go
// handlers/invoices/invoices.go
package invoices

import (
	"go.laravel.com/web"

	"app/services"
)

func Store(r *web.Request) *web.Response {
	if err := services.From(r).Billing.Charge(r, 2000); err != nil {
		return web.Fail(err)
	}

	return web.Back()
}
```

<a name="in-jobs-commands-and-domain-packages"></a>

### In jobs, commands, and domain packages


ハンドラー以外では、関数は `*web.Request` の代わりに `ctx context.Context` を受け取ります。その `ctx` を `services.From(ctx)` に渡せば、キューに入れたジョブ、イベントリスナ、コンソールコマンド、スケジュールタスク、ハンドラーのどこからでもコードを使用できます。次のキュージョブは、同じ `Billing` クライアントで請求書の決済を行います。

```go
// jobs/charge_invoice.go
package jobs

import (
	"context"

	"app/services"
)

type ChargeInvoice struct {
	AmountCents int64
}

func (j ChargeInvoice) Handle(ctx context.Context) error {
	return services.From(ctx).Billing.Charge(ctx, j.AmountCents)
}
```


インストールしたパッケージは独自にサービスを登録し、`inspire.From(r)` などの `From` を公開します。作成方法は [services](/ja/go/docs/packages#services) を参照してください。

<a name="organizing-services-as-your-application-grows"></a>

## Organizing services as your application grows


小さなアプリケーションなら `services` 内に小さな設定構造体やヘルパを置けます。規模が増えたら `services` を薄く保ち、`services/services.go` は `Services`、`New`、`From` に集中させ、連携先やドメインをそれぞれルート階層のパッケージに分けます。

```text
bootstrap/
    app.go              # Registers Services: laravel.BuildServices(services.New)
services/
    services.go         # Holds Services, New, and From
billing/
    client.go           # Stripe client and types
    middleware.go       # billing.Subscribed middleware
search/
    client.go           # Search index client
geo/
    geocoder.go         # Geocoder interface
    mapbox.go           # Mapbox implementation
orders/
    place.go            # Domain functions such as orders.Place(ctx, ...)
handlers/
    orders/             # HTTP handlers calling orders.Place(r, ...)
jobs/
    charge_invoice.go   # Queued jobs calling services.From(ctx) or orders
```


`services/` の全ファイルは同じ `package services` です。十個の連携を同居させると、衝突回避のため `StripeClient`、`StripeError`、`SearchClient`、`SearchError` など全型やヘルパに接頭辞が要ります。分ければ `billing.Client`、`search.Client`、`geo.Geocoder` と明確になり、`billing.Subscribed` を `billing.Client` の隣に置くなど関連コードをまとめられます。

<a name="what-belongs-on-services"></a>

### What belongs on `Services`


起動時設定、外部 SDK や接続プール、再利用する `httpclient.Client`、バッファ付きメトリクスライターなど共有状態を必要とする値は、`services.Services` に追加します。


状態を持たないドメインロジックに構造体や `Services` フィールドは不要です。空の `OrderService` を `services.New` に登録せず、`orders` などに最初の引数が `ctx context.Context` の関数を書きます。DB クエリ、イベント送信、`services.From(ctx)` の直接呼び出しができます。

```go
// orders/place.go
package orders

import (
	"context"

	"go.laravel.com/model"

	"app/models"
	"app/services"
)

func Place(ctx context.Context, userID int64, totalCents int64) (models.Order, error) {
	if err := services.From(ctx).Billing.Charge(ctx, totalCents); err != nil {
		return models.Order{}, err
	}

	order := models.Order{
		UserID:     userID,
		TotalCents: totalCents,
	}
	if err := model.Create(ctx, &order); err != nil {
		return models.Order{}, err
	}

	return order, nil
}
```


ログインユーザーや現在のテナントなど単一リクエストの値も `Services` に置きません。`r.User`（`ctx` なら `auth.User`）で読むか、[adding values of your own](/ja/go/docs/context#adding-values-of-your-own) のようにコンテキストへ値を追加します。

<a name="avoiding-import-cycles"></a>

### Avoiding import cycles


Go は循環 import を禁止するため、パッケージの依存は一方向になります。

```text
bootstrap -> handlers, jobs, commands -> orders -> services -> billing, search, geo
```


- `bootstrap` はルート、ハンドラー、ジョブ、コマンド、`services` を import します。
- `handlers`、`jobs`、`commands`、`listeners`、`orders` などは `services.From(ctx)` を呼ぶため `services` を import します。
- `services` は `services.New` で構築する `billing`、`search`、`geo` などを import します。


`services` が `billing` を import するため、`billing` パッケージから `services` を import してはいけません。`billing` に別のサービスが必要なら、[depending on other services](#depending-on-other-services) のように `billing.NewClient` の引数で受け取り、`services.New` から渡します。連携パッケージを `services` から独立させると、単体テストでも直接テストしやすくなります。

<a name="shared-state-and-concurrency"></a>

## Shared state and concurrency


全 HTTP リクエスト、キュージョブ、リスナ、コマンドは `services.New` が作った同じ `*services.Services` を共有します。`Services` 内のサービスは複数の goroutine から同時に呼んでも安全でなければなりません。


ユーザーやロケールなどのリクエスト単位の値をサービスのフィールドへ保存してはいけません。引数で渡すか `ctx` から読みます。キャッシュマップやメトリクスバッファなど変更可能な状態は `sync.Mutex` やアトミックな値で保護し、`go test -race ./...` でデータ競合を早期に検出してください。

<a name="testing-with-services"></a>

## Testing with services


`tests.New(t)` を呼ぶ各テストは、その環境（`.env.testing` または `.env`、`tests/tests.go` と個別の `laraveltest.Env` による上書き）から新しい `*services.Services` を構築します。共有しないため、機能テストの外部依存を次の三通りで制御できます。


1. **テスト環境変数を渡します。** `services.New` が読む特定の設定には、`laraveltest.Env(map[string]string{"BILLING_CURRENCY": "eur"})` のように `tests.New` へ `laraveltest.Env` を渡します。
2. **`services.From(client.Context())` のフィールドを置き換えます。** 送信前に、フェイクや `httptest.Server` を指すクライアントを `Services` に代入します。例は `services.From(client.Context()).Geocoder = &fakeGeocoder{}` です。終了時の復元は不要です。
3. **`httpclienttest` で HTTP リクエストをフェイク化します。** Laravel の `httpclient` を使うサービスなら、交換せず `httpclienttest.New(t, client)` で外部呼び出しをフェイク化できます。


サービス交換と HTTP レスポンスのフェイクの完全な例は [replacing dependencies](/ja/go/docs/testing#replacing-dependencies) と [testing](/ja/go/docs/http-client#testing) を参照してください。