PHPackages                             brain/context - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. brain/context

ActiveLibrary[Templating &amp; Views](/categories/templating)

brain/context
=============

No-dependencies package to provide context to templates based on query.

2.0.0(4y ago)201.0k4MITPHPPHP &gt;=7.1

Since Sep 15Pushed 4y ago3 watchersCompare

[ Source](https://github.com/Brain-WP/Context)[ Packagist](https://packagist.org/packages/brain/context)[ RSS](/packages/brain-context/feed)WikiDiscussions master Synced today

READMEChangelog (3)Dependencies (7)Versions (6)Used By (0)

Context
=======

[](#context)

Context is package that aims to collect "context" to pass to templates based on a query object.

**Best paired with a template engine**. And maybe with [Hierarchy](https://github.com/Brain-WP/Hierarchy).

---

[![PHP Quality Assurance](https://github.com/Brain-WP/Context/actions/workflows/php-qa.yml/badge.svg?branch=master)](https://github.com/Brain-WP/Context/actions/workflows/php-qa.yml)[![codecov.io](https://camo.githubusercontent.com/15cb40fc8bf94b01c553b63bfb7c2ac7639f191c67e29ba565563547a3375141/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f427261696e2d57502f436f6e746578742e7376673f7374796c653d666c61742d737175617265)](http://codecov.io/github/Brain-WP/Context?branch=master)[![license](https://camo.githubusercontent.com/69f8fccbb73f2d0face7d5a4deaee79e7d7c44b542002564d9e13b98876304c8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f627261696e2f636f6e746578742e7376673f7374796c653d666c61742d737175617265)](http://opensource.org/licenses/MIT)[![release](https://camo.githubusercontent.com/b083e9b2b232e9268c900c29a06f06977bdfa83003e7d548a7b5e242a0664123/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f427261696e2d57502f436f6e746578742e7376673f7374796c653d666c61742d737175617265)](https://github.com/Brain-WP/Context/releases/latest)

---

Quick start
-----------

[](#quick-start)

Let's assume a couple of classed designed to provide context for the homepage and the singular view, respectively:

```
use Brain\Context;

class HomepageContext implements Context\ProviderFactory
{
    public function create(\WP_Query $query, LoggerInterface $logger): ?Provider
    {
        return Context\Provider\ArrayMerge::new(fn() => $query->is_front_page())
            ->addProvider(new MyHeroProvider())
            ->addProvider(new Context\Provider\Posts(['posts_per_page' => 5], 'latest_posts'));
    }
}

class SingularContext implements Context\ProviderFactory
{
    public function create(\WP_Query $query, LoggerInterface $logger): ?Provider
    {
        return Context\Provider\ArrayMerge::new(fn() => $query->is_singular())
            ->addProvider(new Context\Provider\ByCallback(fn() => ['post' => $query->post]))
            ->addProvider(new Context\Provider\Comments(['post_id' => $query->post->ID]));
    }
}
```

Now we can make use of the `Context` class to generate the context for our templates:

```
namespace MyTheme;

use Brain\Context;

add_action('template_redirect', function () {

    $context = Context\Context::new()
        ->withProviderFactory(new HomepageContext())
        ->withProviderFactory(new SingularContext())
        ->provide();

    // pass context to templates here ...
});
```

`Context` class emit the action `"brain.context.providers" that can be used to add providers from different places:

```
namespace MyTheme;

use Brain\Context;

add_action('brain.context.providers', function (Context\Context $context) {
    $context
        ->withProviderFactory(new HomepageContext())
        ->withProviderFactory(new SingularContext());
});

add_action('template_redirect', function () {
    $context = Context\Context::new()->provide();
    // pass context to templates here ...
});
```

Examples using Hierarchy
------------------------

[](#examples-using-hierarchy)

Here's an example of using context in combination with [Brain Hierarchy](https://github.com/Brain-WP/Hierarchy)to render mustache templates passing them context.

```
namespace My\Theme;

use Brain\Hierarchy\{Finder, Loader, QueryTemplate};
use Brain\Context;

class MustacheTemplateLoader implements Loader\Loader
{
   private $engine;

   public function __construct(\Mustache_Engine $engine)
   {
      $this->engine = $engine;
   }

   public function load(string $templatePath): string
   {
        // It will be possible to hook 'brain.context.providers' to add context providers
        $data = Context\Context::new()
            ->convertEntitiesToPlainObjects()
            ->forwardGlobals()
            ->provide();

        return $this->engine->render(file_get_contents($templatePath), $data);
   }
}

add_action('template_redirect', function() {
    if (!QueryTemplate::mainQueryTemplateAllowed()) {
        return;
    }

    $queryTemplate = new QueryTemplate(
        new Finder\BySubfolder('templates', 'mustache'),
        new MustacheTemplateLoader(new \Mustache_Engine())
    );

    $content = $queryTemplate->loadTemplate(null, true, $found);
    $found and die($content);
});
```

Above is *all* the necessary code to render `*.mustache` templates from a `/templates` subfolder in current theme (or parent theme, if any), according to WP template hierarchy, passing to templates context data that can be extended via ad-hoc "view context" classes which will implement `Context\ProviderFactory` interface.

Providers
---------

[](#providers)

### Composite providers

[](#composite-providers)

The "Quick start" section above uses `Context\Provider\ArrayMerge` class to "merge" several providers.

Besides that class, there's also a `Context\Provider\ArrayMergeRecursive` "composite" provider.

### Atomic providers

[](#atomic-providers)

The "composite" providers merge multiple "atomic" providers that can be either custom (anything implementing `Context\Provider`) or one of the shipped provider classes:

- `ByArray` - which provides a given array as-is
- `ByCallback` - which provides an array returned by a given callback
- `Comments` - which provides an array of comments using given comment query arguments
- `Posts` - which provides an array of posts using given post query arguments
- `Subquery` - which provides a `WP_Query` instance using given query arguments
- `Terms` - which provides an array of comments using given taxonomy terms query arguments
- `Users` - which provides an array of comments using given user query arguments

### Custom providers

[](#custom-providers)

The `Context\Provider` interface has a single method:

```
public function provide(\WP_Query $query, LoggerInterface $logger): ?array;
```

Which can be implemented to build custom providers. In the case the provider should not be used based on conditions, it can return `null`.

The given PSR-3 logger interface can be used to log errors and distinguish a provider that returns null due to errors form another that returns `null` because, for example, not targeting the current query.

Logger
------

[](#logger)

All providers support a PSR-3 logger. `Context` class implements PSR-3 `LoggerAwareInterface`, so it is possible to call `setLogger` when instantiating it.

There's also a `"brain.context.logger"` action that passes a callback that can be used to set the logger:

```
add_action('brain.context.logger', function (callable $setter) {
    $setter(new MyPsr3Logger());
});
```

Requirements
------------

[](#requirements)

Context requires **PHP 7.1+** and [Composer](https://getcomposer.org/) to be installed.

Installation
------------

[](#installation)

Best served by Composer, available on Packagist with name [`brain/context`](https://packagist.org/packages/brain/context).

License
-------

[](#license)

Context is released under MIT.

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity27

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~986 days

Total

3

Last Release

1606d ago

Major Versions

1.0.1 → 2.0.02022-02-09

PHP version history (2 changes)1.0.0PHP &gt;=5.5

2.0.0PHP &gt;=7.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2208282?v=4)[Giuseppe Mazzapica](/maintainers/gmazzap)[@gmazzap](https://github.com/gmazzap)

---

Top Contributors

[![gmazzap](https://avatars.githubusercontent.com/u/2208282?v=4)](https://github.com/gmazzap "gmazzap (46 commits)")

---

Tags

hierarchytemplate-enginewordpresswordpress

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/brain-context/health.svg)

```
[![Health](https://phpackages.com/badges/brain-context/health.svg)](https://phpackages.com/packages/brain-context)
```

###  Alternatives

[symfony/symfony

The Symfony PHP framework

31.4k87.2M2.2k](/packages/symfony-symfony)[symfony/http-kernel

Provides a structured process for converting a Request into a Response

8.1k869.4M8.8k](/packages/symfony-http-kernel)[symfony/cache

Provides extended PSR-6, PSR-16 (and tags) implementations

4.2k373.5M3.3k](/packages/symfony-cache)[matomo/matomo

Matomo is the leading Free/Libre open analytics platform

21.7k38.9k](/packages/matomo-matomo)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[ecotone/ecotone

Enterprise architecture layer for Laravel and Symfony — CQRS, Event Sourcing, Durable Workflows (Sagas, Orchestrators), Projections, and Outbox messaging via PHP attributes.

564576.7k53](/packages/ecotone-ecotone)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
