helick/blocks

Helick 块

v1.2.3 2019-11-26 20:53 UTC

This package is auto-updated.

Last update: 2024-09-27 07:57:01 UTC


README

Latest Version on Packagist Total Downloads Software License Quality Score

该软件包帮助您使用 Carbon Fields 轻松创建 Gutenberg 块。

要求

在继续之前,请确保已安装所有依赖项

安装

通过 Composer 安装

$ composer require helick/blocks

使用方法

在您的主题中声明您的块,附加其字段,并为您提供模板的数据

use Carbon_Fields\Field;
use Helick\Blocks\Block;
use WP_Query;

final class ExampleBlock extends Block
{
    /**
     * The block's display name.
     *
     * @var string
     */
    protected $name = 'Example';

    /**
     * The block's description.
     *
     * @var string
     */
    protected $description = 'This is an example block';

    /**
     * The block's template.
     *
     * @var string|string[]
     */
    protected $template = 'partials/blocks/example.php';

    /**
     * Fields to be attached to the block.
     *
     * @return array
     */
    public function fields(): array
    {
        return [
            Field::make('text', 'heading', 'Heading'),
            Field::make('image', 'image', 'Image'),
            Field::make('rich_text', 'content', 'Content'),
            Field::make('association', 'associations', 'Associations')
                 ->set_types([
                     [
                         'type'      => 'post',
                         'post_type' => 'post',
                     ]
                 ])
        ];
    }

    /**
     * Data to be passed to the rendered block.
     *
     * @param array $fields
     *
     * @return array
     */
    public function with(array $fields): array
    {
        return [
            'associations' => $this->queryAssociations($fields['associations'])
        ];
    }

    /**
     * Query the associations.
     *
     * @param array $associations
     *
     * @return WP_Query
     */
    private function queryAssociations(array $associations): WP_Query
    {
        $associationIds = array_column($associations, 'id');
        $associationIds = array_map('intval', $associationIds);

        return new WP_Query([
            'no_found_rows' => true,
            'post__in'      => $associationIds,
            'orderby'       => 'post__in',
        ]);
    }
}

创建您的块模板

<div class="block">
    <div class="block__heading">
        <h1><?= esc_html($fields['heading']) ?></h1>
    </div>
    <div class="block__image">
        <?= wp_get_attachment_image($fields['image'], 'full') ?>
    </div>
    <div class="block__content">
        <?= apply_filters('the_content', $fields['content']) ?>
    </div>
    <?php if ($associations->have_posts()) : ?>
        <div class="block__associations">
            <ul class="block__associations-list">
                <?php while ($associations->have_posts()) : $associations->the_post(); ?>
                    <li class="block__associations-item">
                        <a class="block__associations-link" href="<?= esc_url(get_the_permalink()) ?>">
                            <?= esc_html(get_the_title()) ?>
                        </a>
                    </li>
                <?php endwhile; ?>
            </ul>
        </div>
        <?php wp_reset_postdata(); ?>
    <?php endif; ?>
</div>

最后,在主题的 functions.php 中注册您的块

ExampleBlock::boot();

缓存

最简单、可能是最好的方法是将 完整的 HTML 输出 缓存起来,PHP 的输出缓冲函数将帮助我们实现这一点,而无需移动太多代码

use Carbon_Fields\Field;
use Helick\Blocks\Block;
use Exception;

final class ExampleBlock extends Block
{
    // Your block declaration goes in here ...

    /**
     * Render the block.
     *
     * @param array $fields
     * @param array $attributes
     * @param array $blocks
     *
     * @return void
     *
     * @throws Exception
     */
    public function render(array $fields, array $attributes, array $blocks): void
    {
        // Compose the render arguments
        $args = compact('fields', 'attributes', 'blocks');

        // Generate cache key based on the given arguments
        $cacheKey   = sprintf('example_block_%s', hash('md5', wp_json_encode($args)));
        $cacheGroup = 'blocks';

        // Check whether we have the block's cached output
        $output = wp_cache_get($cacheKey, $cacheGroup);

        // If nothing is found, catch the block render output
        if (false === $output) {
            ob_start();

            try {
                parent::render($fields, $attributes, $blocks);
            } catch (Exception $e) {
                // In case something goes wrong we clear the output buffer
                ob_end_clean();

                // Re-throw an exception so we don't cache the actual error output
                throw $e;
            }

            $output = ob_get_clean();

            // Cache the block's output for 5 minutes (300 secs)
            wp_cache_set($cacheKey, $output, $cacheGroup, 5 * MINUTE_IN_SECONDS);
        }

        echo $output;
        echo "<!-- Cache Key: {$cacheKey} -->";
    }
}

这样我们只将实际输出存储在我们的缓存中,没有帖子、没有元数据、没有术语。只有 HTML。

您也可以使用 WP CLI 检查您的缓存

# Get the block's output from the object cache
$ wp cache get example_block_098f6bcd4621d373cade4e832627b4f6 blocks
...your block's output...

# Remove the block's output from the object cache
$ wp cache delete example_block_098f6bcd4621d373cade4e832627b4f6 blocks
Success: Object deleted.

贡献

请参阅 CONTRIBUTINGCODE_OF_CONDUCT 以获取详细信息。

安全

如果您发现任何与安全相关的问题,请通过电子邮件 evgenii@helick.io 而不是使用问题跟踪器。

鸣谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件