tc/front-matter

基于适配器的 PHP 前置元数据解析/导出器

v1.0.0 2017-03-04 02:46 UTC

This package is not auto-updated.

Last update: 2024-09-28 20:55:48 UTC


README

基于适配器的 PHP 前置元数据解析/导出器

安装

composer require tc/front-matter

适配器

  • YAML
  • JSON

示例用法

<?php

use Tc\FrontMatter\FrontMatter;
use Tc\FrontMatter\Adapter\JsonAdapter;

// sample yaml front matter
$fileContent = '---
title: A Title
slug: a-slug
created: 2017-01-01 12:00
---
This is some sample content
';

// create a new parser/dumper
$frontMatter = new FrontMatter();

// parse file contents
$document = $frontMatter->parse($fileContent);

// get data
$document->getData();

// get content
$document->getContent();

// dump the document back to front matter string
$dump = $frontMatter->dumpDocument($document);

// dump data and content back to front matter string
$dump = $frontMatter->dump(['foo' => 'bar'], 'Hello World');

// parse JSON front matter
$jsonAdapter = new JsonAdapter();

// create new parser/dumper using the json adaptor
$frontMatter = new FrontMatter($jsonAdapter);

// sample json front matter
$fileContent = '---
{
    "title": "A Title",
    "slug": "a-slug",
    "created": "2017-01-01 12:00"
}
---
This is some sample content
';

// parse file contents
$document = $frontMatter->parse($fileContent);

Symfony 集成

要启用 symfony 集成,请将包添加到您的内核中

new Tc\FrontMatter\Bridge\Symfony\TcFrontMatterBundle(),

现在您可以使用前置元数据服务:

  • YAML tc.front_mattertc.front_matter.yaml
  • JSON tc.front_matter.json

示例

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        $file = file_get_contents('./path/to/front-matter-file');
        $document = $this->get('tc.front_matter')->parse($file);

        return $this->render('default/index.html.twig', [
            'content' => $document->getContent(),
            'data' => $document->getData()
        ]);
    }
}

自定义适配器

您可以创建自己的自定义适配器以解析和导出前置元数据。

您只需实现 Tc\FrontMatter\Adapter\AdapterInterface

然后您可以使用您的适配器创建一个新的前置元数据实例。例如:

<?php

$myFrontMatter = new FrontMatter(new FooAdapter());

如果您正在使用 symfony,可以将您的适配器注册为服务,并标记它们。例如:

foo_adapter:
    class: 'AppBundle\Adapter\FooAdapter'
    tags:
        - {name: tc.front_matter.adapter, adapter_name: foo}

前置元数据包将自动为您生成一个前置元数据服务: tc.front_matter.foo

许可证

Tc Front Matter 使用 MIT 许可证授权。

请参阅 LICENSE 获取更多详细信息。