본문으로 건너뛰기
Services
Architecture Concepts
Laravel Go 0.x · 한국어 문서https://laravel.com/go/docs/0.x/services

Services

Introduction​

대부분의 애플리케이션은 결제 프로바이더 클라이언트, 검색 클라이언트, 지오코더처럼 시작 시 한 번 만들고 여러 핸들러와 잡에서 공유하는 의존성을 사용합니다. 요청마다 만들면 연결을 낭비하고 환경 조회를 반복하게 됩니다. 반대로 모든 의존성을 라우트 파일, 잡 구조체, 헬퍼 함수에 전달하면 모든 시그니처가 복잡해집니다.

services/services.go의 services 패키지로 해결할 수 있습니다. 공유 의존성을 담는 Services 구조체, 시작 시 환경에서 한 번 구성하는 New, 요청이나 context에서 다시 읽는 From을 정의합니다.

// 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와 설정만 추가합니다.

Building your services​

Stripe 등 외부 서비스와 통신한다면 billing 같은 별도 패키지에 클라이언트를 만들고 services/services.go에서 인스턴스를 연결합니다. 다음 billing 패키지는 Client 타입 뒤에 결제 프로바이더를 감쌉니다.

// 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, 운영에서는 프로세스 환경에서 변수를 읽습니다.

// 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를 참조하세요.

STRIPE_KEY 같은 비밀 값은 services.New에서 빈 대체값을 주고 키 없이 실제로 클라이언트를 호출할 때 오류를 반환합니다. Laravel은 모든 콘솔 명령어에서 서비스를 구성하므로 services.New에서 실패하면 아직 .env가 없는 새 복제본에서 laravel key:generate 같은 명령어도 실행할 수 없습니다.

Depending on other services​

서비스가 다른 서비스를 필요로 한다면 services.New에서 첫 의존성을 만든 뒤 두 번째 생성자에 전달합니다. 예를 들어 billing.Client가 카드 결제 전 판매세 계산에 tax.Calculator를 필요로 하면 taxCalculator를 먼저 만들고 billing.NewClient에 전달합니다.

// 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 컴파일러가 실행 전에 빠진 인수를 찾습니다.

Interfaces and concrete types​

처음에는 Services에서 *billing.Client 같은 구체 포인터 타입을 사용합니다. 구현이 여러 개이거나 테스트 HTTP 서버 없이 가벼운 인메모리 페이크로 교체하려면 인터페이스 필드를 사용합니다.

예를 들어 geo 패키지는 Mapbox 구현과 작은 Geocoder 인터페이스를 함께 정의할 수 있습니다.

// 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에서 운영용 구현을 연결합니다.

// 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", "")),
}
}

Reusable HTTP clients​

연동에 기본 URL, Bearer 토큰과 타임아웃 설정만 필요하면 별도 래퍼 패키지는 필요 없습니다. 재사용할 *httpclient.Client 템플릿을 Services에 직접 저장합니다.

// 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를 참조하세요.

Using services​

In handlers and middleware​

핸들러나 middleware에서 요청 r을 services.From에 전달하면 서비스를 읽을 수 있습니다.

// 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()
}

In jobs, commands, and domain packages​

핸들러 밖에서는 함수가 *web.Request 대신 ctx context.Context를 받습니다. 이 ctx를 services.From(ctx)에 전달하면 큐에 넣은 잡, 이벤트 리스너, 콘솔 명령어, 예약 태스크, 핸들러 어디서든 코드를 사용할 수 있습니다. 다음 큐 잡은 같은 Billing 클라이언트로 청구서를 결제합니다.

// 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를 참조하세요.

Organizing services as your application grows​

작은 애플리케이션에서는 services 디렉터리에 작은 설정 구조체나 짧은 헬퍼를 두어도 좋습니다. 규모가 커지면 services를 얇게 유지하고 services/services.go는 Services, New, From에 집중하도록 합니다. 각 실제 연동이나 도메인은 루트 수준의 별도 패키지에 둡니다.

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 옆에 두는 등 관련 코드를 함께 둘 수 있습니다.

What belongs on Services​

시작 시 설정, 외부 SDK나 연결 풀, 재사용 httpclient.Client, 버퍼가 있는 메트릭 작성기 같은 공유 프로세스 상태가 필요한 값이면 services.Services에 필드를 추가합니다.

상태 없는 도메인 로직에는 구조체나 Services 필드가 필요 없습니다. 필드 없는 OrderService를 만들고 services.New에 등록하는 대신 orders 같은 도메인 패키지에 첫 인수가 ctx context.Context인 일반 함수를 작성합니다. 데이터베이스 쿼리, 이벤트 발송, services.From(ctx) 직접 호출이 가능합니다.

// 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처럼 컨텍스트에 붙입니다.

Avoiding import cycles​

Go는 순환 패키지 import를 금지하므로 의존성은 한 방향으로 흐릅니다.

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처럼 billing.NewClient의 파라미터로 받고 services.New에서 전달합니다. 연동 패키지를 services와 독립적으로 유지하면 단위 테스트에서도 직접 테스트하기 쉽습니다.

Shared state and concurrency​

모든 HTTP 요청, 큐 잡, 리스너, 콘솔 명령어는 services.New가 만든 같은 *services.Services를 공유합니다. 따라서 Services에 저장한 서비스는 여러 고루틴이 동시에 호출해도 안전해야 합니다.

사용자나 로케일 같은 요청별 값을 서비스 구조체 필드에 저장하지 마세요. 메서드 인수로 전달하거나 ctx에서 읽습니다. 캐시 맵이나 메트릭 버퍼처럼 변경 가능한 메모리 상태가 있다면 sync.Mutex나 원자적 값으로 보호하고 go test -race ./...로 조기에 데이터 경합을 찾습니다.

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와 HTTP 클라이언트의 testing을 참조하세요.