brain/context

无依赖的包,为基于查询的模板提供上下文。

2.0.0 2022-02-09 07:39 UTC

This package is auto-updated.

Last update: 2024-09-09 19:49:24 UTC


README

Context 是一个旨在根据查询对象收集 "上下文" 以传递给模板的包。

最佳搭配模板引擎。也许还可以搭配 Hierarchy

PHP Quality Assurance codecov.io license release

快速开始

假设有两个类,分别用于为首页和单篇文章视图提供上下文

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]));
    }
}

现在我们可以利用 Context 类来为我们的模板生成上下文

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 类会发出 `"brain.context.providers"` 动作,可以用于从不同地方添加提供者

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 ...
});

使用 Hierarchy 的示例

下面是一个使用上下文结合 Brain Hierarchy 来渲染 mustache 模板并传递上下文的示例。

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);
});

上面是渲染来自当前主题(或父主题,如果有)的 /templates 子目录下的 *.mustache 模板的 所有 必要代码,根据 WP 模板层次结构,将可以通过实现 Context\ProviderFactory 接口的 "视图上下文" 类扩展的上下文数据传递给模板。

提供者

组合提供者

上面的 "快速开始" 部分使用 Context\Provider\ArrayMerge 类来 "合并" 几个提供者。

除了这个类,还有一个 Context\Provider\ArrayMergeRecursive "组合" 提供者。

原子提供者

"组合" 提供者合并多个 "原子" 提供者,这些提供者可以是自定义的(任何实现 Context\Provider 的内容)或提供的提供者类之一

  • ByArray - 提供一个给定的数组
  • ByCallback - 提供一个由给定的回调返回的数组
  • Comments - 提供一个使用给定的评论查询参数的评论数组
  • Posts - 提供一个使用给定的文章查询参数的文章数组
  • Subquery - 提供一个使用给定的查询参数的 WP_Query 实例
  • Terms - 提供一个使用给定的分类术语查询参数的术语数组
  • Users - 提供一个使用给定的用户查询参数的用户数组

自定义提供者

Context\Provider 接口有一个单独的方法

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

可以实现来构建自定义提供者。如果提供者根据条件不应使用,则可以返回 null

给定的 PSR-3 日志接口可用于记录错误,并区分由于错误而返回 null 的提供者和由于例如未针对当前查询而返回 null 的提供者。

记录器

所有提供者都支持 PSR-3 记录器。 Context 类实现了 PSR-3 LoggerAwareInterface,因此在实例化时可以调用 setLogger

还有一个 "brain.context.logger" 动作,它传递一个回调,可以用来设置记录器

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

需求

Context 需要 PHP 7.1+ 和已安装的 Composer

安装

最佳通过 Composer 安装,可在 Packagist 上找到,名称为 brain/context

许可证

Context 根据 MIT 许可证发布。