# 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](/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`를 만들고 병렬 테스트에 영향을 주지 않으며 필드를 교체할 수 있습니다.


데이터베이스, 캐시, 메일러, 스토리지 디스크와 큐 같은 Laravel 내장 시스템은 `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`가 숫자를 기대하는데 텍스트가 있는 등 환경 변수 값이 유효하지 않으면 Laravel은 시작을 중단하고 문제를 표시합니다. `env`에서 타입이 있는 변수를 읽는 방법은 설정 가이드의 [your own settings](/go/docs/configuration#your-own-settings)를 참조하세요.

> [!NOTE]
> `STRIPE_KEY` 같은 비밀 값은 `services.New`에서 빈 대체값을 주고 키 없이 실제로 클라이언트를 호출할 때 오류를 반환합니다. Laravel은 모든 콘솔 명령어에서 서비스를 구성하므로 `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](/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](/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)
}
```


설치된 Laravel 패키지는 자체 서비스를 따로 등록하고 `inspire.From(r)` 같은 자체 `From` 헬퍼를 제공합니다. 서비스가 있는 패키지 작성법은 패키지 개발 가이드의 [services](/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/`의 모든 파일은 같은 Go 패키지(`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`인 일반 함수를 작성합니다. 데이터베이스 쿼리, 이벤트 발송, `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](/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`에 저장한 서비스는 여러 고루틴이 동시에 호출해도 안전해야 합니다.


사용자나 로케일 같은 요청별 값을 서비스 구조체 필드에 저장하지 마세요. 메서드 인수로 전달하거나 `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](/go/docs/testing#replacing-dependencies)와 HTTP 클라이언트의 [testing](/go/docs/http-client#testing)을 참조하세요.