Services
- Introduction
- Building your services
- Using services
- Organizing services as your application grows
- Shared state and concurrency
- Testing with services
Introduction
Most applications rely on dependencies they build once at startup and share across many handlers and jobs, such as a payment provider's client, a search client, or a geocoder. Building a client on every request wastes connections and repeats environment lookups, while threading every dependency down through route files, job structs, and helper functions adds clutter to every signature.
Applications can solve this with the services package in services/services.go. It defines a Services struct that holds your application's shared dependencies, a New function that constructs them from your environment once at startup, and a From function that reads them back from any request or context:
1// services/services.go2package services34import (5 "context"67 laravel "go.laravel.com"8 "go.laravel.com/config"9)1011type Services struct{}1213func New(env *config.Env, app *laravel.App) Services {14 return Services{}15}1617func From(ctx context.Context) *Services {18 return laravel.ServicesOf[*Services](ctx)19}1// services/services.go2package services34import (5 "context"67 laravel "go.laravel.com"8 "go.laravel.com/config"9)1011type Services struct{}1213func New(env *config.Env, app *laravel.App) Services {14 return Services{}15}1617func From(ctx context.Context) *Services {18 return laravel.ServicesOf[*Services](ctx)19}
In bootstrap/app.go, Services: laravel.BuildServices(services.New) registers your constructor with the application. Laravel calls services.New once after building its own subsystems (such as the database, cache, queue, and tracing) and attaches the resulting *Services to the application. Because your services live on the application rather than in package-level globals, every test builds its own isolated Services and can swap fields without affecting other tests running in parallel.
Laravel's built-in subsystems (the database, cache, mailer, storage disks, and queue) are already attached to the context through their own packages, such as db.Table and mail.To. You only add your application's own clients, SDKs, and custom settings to services.Services.
Building your services
When your application talks to an external service such as Stripe, write the client in a package of its own, such as billing, and wire an instance of it in services/services.go. For example, this billing package wraps your payment provider behind a Client type:
1// billing/client.go2package billing34import (5 "context"6 "errors"7 "net/url"8 "strconv"910 "go.laravel.com/httpclient"11)1213type Client struct {14 key string15 currency string16}1718func NewClient(key, currency string) *Client {19 return &Client{key: key, currency: currency}20}2122func (c *Client) Charge(ctx context.Context, cents int64) error {23 if c.key == "" {24 return errors.New("billing: STRIPE_KEY is not set")25 }2627 _, err := httpclient.Token(c.key).28 Form(url.Values{29 "amount": {strconv.FormatInt(cents, 10)},30 "currency": {c.currency},31 }).32 EnsureSuccessful().33 Post(ctx, "https://api.stripe.com/v1/payment_intents")3435 return err36}1// billing/client.go2package billing34import (5 "context"6 "errors"7 "net/url"8 "strconv"910 "go.laravel.com/httpclient"11)1213type Client struct {14 key string15 currency string16}1718func NewClient(key, currency string) *Client {19 return &Client{key: key, currency: currency}20}2122func (c *Client) Charge(ctx context.Context, cents int64) error {23 if c.key == "" {24 return errors.New("billing: STRIPE_KEY is not set")25 }2627 _, err := httpclient.Token(c.key).28 Form(url.Values{29 "amount": {strconv.FormatInt(cents, 10)},30 "currency": {c.currency},31 }).32 EnsureSuccessful().33 Post(ctx, "https://api.stripe.com/v1/payment_intents")3435 return err36}
Next, add a Billing field to Services and construct the client inside services.New. Laravel passes the same *config.Env it uses to read its own settings, so your variables come from .env locally and from the process environment in production:
1// services/services.go2package services34import (5 "context"67 laravel "go.laravel.com"8 "go.laravel.com/config"910 "app/billing"11)1213type Services struct {14 Billing *billing.Client15}1617func New(env *config.Env, app *laravel.App) Services {18 return Services{19 Billing: billing.NewClient(20 env.String("STRIPE_KEY", ""),21 env.String("BILLING_CURRENCY", "usd"),22 ),23 }24}2526func From(ctx context.Context) *Services {27 return laravel.ServicesOf[*Services](ctx)28}1// services/services.go2package services34import (5 "context"67 laravel "go.laravel.com"8 "go.laravel.com/config"910 "app/billing"11)1213type Services struct {14 Billing *billing.Client15}1617func New(env *config.Env, app *laravel.App) Services {18 return Services{19 Billing: billing.NewClient(20 env.String("STRIPE_KEY", ""),21 env.String("BILLING_CURRENCY", "usd"),22 ),23 }24}2526func From(ctx context.Context) *Services {27 return laravel.ServicesOf[*Services](ctx)28}
If an environment variable holds an invalid value, such as text where env.Int expects a number, Laravel stops at startup and lists the problem. To learn more about reading typed variables from env, check out the configuration guide's section on your own settings.
Give secrets such as STRIPE_KEY an empty fallback in services.New, and return an error when the client is actually called without a key. Laravel builds your services for every console command, so failing during services.New would stop commands such as laravel key:generate from running on a fresh clone with no .env file yet.
Depending on other services
When one service needs another, construct the first dependency in services.New and pass it into the second service's constructor. For example, if your billing.Client needs a tax.Calculator to compute sales tax before charging a card, build taxCalculator first and hand it to billing.NewClient:
1// services/services.go2func New(env *config.Env, app *laravel.App) Services {3 taxCalculator := tax.NewCalculator(env.String("TAX_API_KEY", ""))45 billingClient := billing.NewClient(6 env.String("STRIPE_KEY", ""),7 env.String("BILLING_CURRENCY", "usd"),8 taxCalculator,9 )1011 return Services{12 Tax: taxCalculator,13 Billing: billingClient,14 }15}1// services/services.go2func New(env *config.Env, app *laravel.App) Services {3 taxCalculator := tax.NewCalculator(env.String("TAX_API_KEY", ""))45 billingClient := billing.NewClient(6 env.String("STRIPE_KEY", ""),7 env.String("BILLING_CURRENCY", "usd"),8 taxCalculator,9 )1011 return Services{12 Tax: taxCalculator,13 Billing: billingClient,14 }15}
Passing dependencies explicitly keeps the graph visible in one place and lets the Go compiler catch missing arguments before your application ever runs.
Interfaces and concrete types
Start with concrete pointer types on Services, such as *billing.Client. Reach for an interface field when you have more than one implementation or want to drop in a lightweight in-memory fake in tests without starting an HTTP test server.
For example, a geo package might define a small Geocoder interface alongside a Mapbox implementation:
1// geo/geocoder.go2package geo34import "context"56type Coordinates struct {7 Latitude float648 Longitude float649}1011type Geocoder interface {12 Locate(ctx context.Context, address string) (Coordinates, error)13}1// geo/geocoder.go2package geo34import "context"56type Coordinates struct {7 Latitude float648 Longitude float649}1011type Geocoder interface {12 Locate(ctx context.Context, address string) (Coordinates, error)13}
In services/services.go, type the field as the geo.Geocoder interface while wiring the production implementation in New:
1// services/services.go2type Services struct {3 Billing *billing.Client4 Geocoder geo.Geocoder5}67func New(env *config.Env, app *laravel.App) Services {8 return Services{9 Billing: billing.NewClient(10 env.String("STRIPE_KEY", ""),11 env.String("BILLING_CURRENCY", "usd"),12 ),13 Geocoder: geo.NewMapbox(env.String("MAPBOX_TOKEN", "")),14 }15}1// services/services.go2type Services struct {3 Billing *billing.Client4 Geocoder geo.Geocoder5}67func New(env *config.Env, app *laravel.App) Services {8 return Services{9 Billing: billing.NewClient(10 env.String("STRIPE_KEY", ""),11 env.String("BILLING_CURRENCY", "usd"),12 ),13 Geocoder: geo.NewMapbox(env.String("MAPBOX_TOKEN", "")),14 }15}
Reusable HTTP clients
When an integration only needs a configured base URL, bearer token, and timeout, you don't need a wrapper package of your own. Store a reusable *httpclient.Client template directly on Services:
1// services/services.go2type Services struct {3 GitHub *httpclient.Client4}56func New(env *config.Env, app *laravel.App) Services {7 return Services{8 GitHub: httpclient.BaseURL("https://api.github.com").9 Token(env.String("GITHUB_TOKEN", "")).10 AcceptJSON().11 EnsureSuccessful(),12 }13}1// services/services.go2type Services struct {3 GitHub *httpclient.Client4}56func New(env *config.Env, app *laravel.App) Services {7 return Services{8 GitHub: httpclient.BaseURL("https://api.github.com").9 Token(env.String("GITHUB_TOKEN", "")).10 AcceptJSON().11 EnsureSuccessful(),12 }13}
Starting the template from httpclient.BaseURL routes requests through the application in the context you pass to Get or Post, so httpclienttest still intercepts them in tests. To learn more, check out the HTTP client guide's section on base URLs and reusable clients.
Using services
In handlers and middleware
Pass the request r to services.From in any handler or middleware to read your application's services:
1// handlers/invoices/invoices.go2package invoices34import (5 "go.laravel.com/web"67 "app/services"8)910func Store(r *web.Request) *web.Response {11 if err := services.From(r).Billing.Charge(r, 2000); err != nil {12 return web.Fail(err)13 }1415 return web.Back()16}1// handlers/invoices/invoices.go2package invoices34import (5 "go.laravel.com/web"67 "app/services"8)910func Store(r *web.Request) *web.Response {11 if err := services.From(r).Billing.Charge(r, 2000); err != nil {12 return web.Fail(err)13 }1415 return web.Back()16}
In jobs, commands, and domain packages
Outside a handler, functions take a ctx context.Context instead of a *web.Request. Pass that ctx to services.From(ctx) so the code works from a queued job, an event listener, a console command, a scheduled task, or a handler. For example, this queued job charges an invoice using the same Billing client:
1// jobs/charge_invoice.go2package jobs34import (5 "context"67 "app/services"8)910type ChargeInvoice struct {11 AmountCents int6412}1314func (j ChargeInvoice) Handle(ctx context.Context) error {15 return services.From(ctx).Billing.Charge(ctx, j.AmountCents)16}1// jobs/charge_invoice.go2package jobs34import (5 "context"67 "app/services"8)910type ChargeInvoice struct {11 AmountCents int6412}1314func (j ChargeInvoice) Handle(ctx context.Context) error {15 return services.From(ctx).Billing.Charge(ctx, j.AmountCents)16}
Installed Laravel packages register their own services separately and expose their own From helper, such as inspire.From(r). To learn more about writing a package with services of its own, check out the package development guide's section on services.
Organizing services as your application grows
In a small application, putting a tiny settings struct or a short helper file inside the services directory works fine. As your application grows, keep the services package thin so services/services.go stays focused on the Services struct, New, and From, and place each real integration or domain area in its own root-level package:
1bootstrap/2 app.go # Registers Services: laravel.BuildServices(services.New)3services/4 services.go # Holds Services, New, and From5billing/6 client.go # Stripe client and types7 middleware.go # billing.Subscribed middleware8search/9 client.go # Search index client10geo/11 geocoder.go # Geocoder interface12 mapbox.go # Mapbox implementation13orders/14 place.go # Domain functions such as orders.Place(ctx, ...)15handlers/16 orders/ # HTTP handlers calling orders.Place(r, ...)17jobs/18 charge_invoice.go # Queued jobs calling services.From(ctx) or orders1bootstrap/2 app.go # Registers Services: laravel.BuildServices(services.New)3services/4 services.go # Holds Services, New, and From5billing/6 client.go # Stripe client and types7 middleware.go # billing.Subscribed middleware8search/9 client.go # Search index client10geo/11 geocoder.go # Geocoder interface12 mapbox.go # Mapbox implementation13orders/14 place.go # Domain functions such as orders.Place(ctx, ...)15handlers/16 orders/ # HTTP handlers calling orders.Place(r, ...)17jobs/18 charge_invoice.go # Queued jobs calling services.From(ctx) or orders
Every file inside services/ is part of the same Go package (package services). Keeping ten integrations in one directory forces you to prefix every type and helper (StripeClient, StripeError, SearchClient, SearchError) so their names don't collide. Putting each integration in its own package keeps names crisp (billing.Client, search.Client, geo.Geocoder) and lets each package co-locate related code, such as putting billing.Subscribed middleware next to billing.Client.
What belongs on Services
Add a field to services.Services when a value needs startup configuration, an external SDK or connection pool, a reusable httpclient.Client, or shared in-process state such as a buffered metrics writer.
Stateless domain logic does not need a struct or a field on Services. Instead of creating a zero-field OrderService struct and registering it in services.New, write plain functions in a domain package such as orders that accept ctx context.Context as their first parameter. Those functions can query the database, dispatch events, and call services.From(ctx) directly:
1// orders/place.go2package orders34import (5 "context"67 "go.laravel.com/model"89 "app/models"10 "app/services"11)1213func Place(ctx context.Context, userID int64, totalCents int64) (models.Order, error) {14 if err := services.From(ctx).Billing.Charge(ctx, totalCents); err != nil {15 return models.Order{}, err16 }1718 order := models.Order{19 UserID: userID,20 TotalCents: totalCents,21 }22 if err := model.Create(ctx, &order); err != nil {23 return models.Order{}, err24 }2526 return order, nil27}1// orders/place.go2package orders34import (5 "context"67 "go.laravel.com/model"89 "app/models"10 "app/services"11)1213func Place(ctx context.Context, userID int64, totalCents int64) (models.Order, error) {14 if err := services.From(ctx).Billing.Charge(ctx, totalCents); err != nil {15 return models.Order{}, err16 }1718 order := models.Order{19 UserID: userID,20 TotalCents: totalCents,21 }22 if err := model.Create(ctx, &order); err != nil {23 return models.Order{}, err24 }2526 return order, nil27}
Values scoped to a single request, such as the logged-in user or the current tenant, don't belong on Services either. Read the user with r.User (or auth.User from a ctx), or attach request-wide values to the request's context as adding values of your own describes.
Avoiding import cycles
Go forbids circular package imports, so your application's packages follow a one-way dependency flow:
1bootstrap -> handlers, jobs, commands -> orders -> services -> billing, search, geo1bootstrap -> handlers, jobs, commands -> orders -> services -> billing, search, geo
bootstrapimports your routes, handlers, jobs, commands, andservices.handlers,jobs,commands,listeners, and domain packages such asordersimportservicesto callservices.From(ctx).servicesimports integration packages such asbilling,search, andgeososervices.Newcan construct them.
Because services imports billing, the billing package must not import services. If billing needs another service, accept it as a parameter in billing.NewClient and pass it in from services.New, as depending on other services shows. Keeping integration packages independent of services also makes them straightforward to test directly in unit tests.
Shared state and concurrency
Every HTTP request, queued job, listener, and console command shares the same *services.Services instance that services.New built. Each service you store on Services must therefore be safe to call from several goroutines at once.
Never store per-request values, such as the logged-in user or a request's locale, in fields on a service struct. Pass request-specific values as method arguments or read them from the ctx argument instead. If a service holds mutable in-memory state, such as a cache map or a metrics buffer, protect that state with a sync.Mutex or atomic values, and run your test suite with go test -race ./... to catch data races early.
Testing with services
Every test that calls tests.New(t) builds its own application with a fresh *services.Services instance created from the test's environment (.env.testing or .env, plus the overrides in tests/tests.go and any per-test laraveltest.Env). Because no test shares services with another, you have three clean ways to control external dependencies in your feature tests:
- Supply test environment variables. Pass
laraveltest.Envtotests.Newwhen a test needs specific settings read byservices.New, such aslaraveltest.Env(map[string]string{"BILLING_CURRENCY": "eur"}). - Replace a field on
services.From(client.Context()). Before sending requests, assign a fake implementation or a client pointed at anhttptest.Serverdirectly onto the test application'sServicesstruct, such asservices.From(client.Context()).Geocoder = &fakeGeocoder{}. Nothing needs to be restored when the test ends. - Fake HTTP requests with
httpclienttest. If a service sends its requests through Laravel'shttpclientpackage, fake the outgoing HTTP calls withhttpclienttest.New(t, client)without replacing the service at all.
To see full examples of swapping services and faking HTTP responses in tests, check out the testing guide's section on replacing dependencies and the HTTP client guide's section on testing.