githubEdit

🔌Service Providers

Service providers are PressGang's hook for bootstrapping services after the framework has initialised. They run after Timber and the Loader are ready, making them the right place for wiring up filters, registering integrations, or initialising third-party libraries.

PressGang ships with one service provider by default — TimberServiceProvider — which registers context managers, Twig extensions, Twig environment options, and snippet template paths. But you can add your own alongside it.

How They Work

1

1. Config declares providers

Class strings are listed in config/service-providers.php. Child theme config replaces the parent file, so always include TimberServiceProvider unless you're intentionally removing it.

2

2. Filter allows modification

The list is passed through the pressgang_service_providers filter, letting plugins or mu-plugins add or remove providers.

3

3. PressGang boots each one

Each class string is validated: it must be a loadable class implementing ServiceProviderInterface. Invalid entries are skipped silently — no fatal errors from a bad config line.

The Interface

Every service provider implements ServiceProviderInterface, which requires exactly one method:

src/ServiceProviders/ServiceProviderInterface.php
namespace PressGang\ServiceProviders;

interface ServiceProviderInterface {
    public function boot(): void;
}
circle-info

Providers are instantiated with no constructor arguments. If your provider needs configuration, read it from Config::get() or WordPress options inside boot().

Default Configuration

TimberServiceProvider wires up:

Concern
Config source
Hook

Context managers

config/context-managers.php

timber/context

Twig extensions

config/twig-extensions.php

timber/twig

Twig environment options

config/timber.php

timber/twig/environment/options

Snippet template paths

vendor directory

timber/locations

See Context Managers and Twig Extensions for details on each.

Writing a Custom Service Provider

1

Create the class

2

Register in config

circle-exclamation

Adding a Provider via Filter

Plugins and mu-plugins can add providers without touching config files:

Guidelines

triangle-exclamation
  • Register hooks in boot(), execute work in callbacks. The boot() method should only call add_action() / add_filter() — not perform queries, remote requests, or heavy computation.

  • One concern per provider. If your provider handles both search customisation and email configuration, split it into two providers.

  • Guard for dependencies. If your provider depends on a plugin (ACF, WooCommerce, etc.), check class_exists() or function_exists() before registering hooks.

  • No constructor arguments. PressGang instantiates providers with new $class(). Use Config::get() or WordPress options for configuration.

Hooks

Hook
Type
Purpose

pressgang_service_providers

filter

Modify the list of service provider class strings before boot

Last updated