MIT License

技术解读

以下内容由 GitRead 中文社区 编辑团队基于项目 README 与官方资料整理, 结合中文开发者的常见使用场景补充技术选型建议。具体以项目官方文档为准。

Log1x/acf-composer 深度技术分析

项目背景与痛点

在现代网页开发中,高级自定义字段(ACF)作为WordPress的一个强大插件,能极大提升网站的灵活性及可用性。然而,随着功能的扩展,开发者往往会面临配置大量字段、块、部件和选项页面的挑战,这些设置不仅繁琐,且容易出错。该项目Log1x/acf-composer正是为解决这一痛点而诞生。它通过采用ACF Builder的方式,使开发者能够以编程化地构建这些配置,简化了配置过程,并提升了可维护性。

技术核心揭秘

该项目的核心技术在于通过编程方式动态产生ACF字段和其他组件,依赖的是ACF和Sage框架的结合。Sage是一个基于Composer的WordPress开发环境,旨在简化开发流程。

技术架构与数据流

具体来看,项目通过composer.json文件依赖管理,自动加载ACF字段和其他配置,减少了手动配置的繁琐性。Mermaid示意图如下:

graph TD A[用户首次加载] --> B[Composer安装依赖] B --> C[构建配置文件] C --> D[生成ACF字段] D --> E[读取配置] E --> F[初始化配置] F --> G[渲染前端]

这是一套典型的依赖注入架构,通过Composer管理依赖项,确保项目依赖的明确性和可重复性。同时,通过优化数据流,保证了项目整体的高效运行。

功能亮点与差异

与同类竞品相比,Log1x/acf-composer的最大亮点在于其简洁、清晰、模块化的配置机制。它很好地利用了Composer进行依赖管理,提高了代码的可维护性和简洁度,使得开发者可以专注于核心功能的开发,而无需过多关注底层配置。

此外,项目的源代码高度模块化,这不仅方便了项目的维护和扩展,也使得其他开发者更容易理解和上手,减少了学习成本。

应用场景与落地建议

在生产环境中使用Log1x/acf-composer时,需要注意以下几点:

  1. 稳定性: 由于项目依赖于Composer进行管理,建议开发和生产环境使用相同的PHP版本和依赖项。
  2. 性能优化: 考虑到大量ACF字段可能会对数据库I/O造成影响,开发者应优化查询和字段配置逻辑,合理使用缓存。
  3. 安全问题: 注意敏感信息的加密存储和处理,避免因其配置机制而引发的安全风险。

该项目非常适合构建复杂而功能丰富的WordPress站点,特别是涉及大量定制化字段和模块的网站。

综合评价

Log1x/acf-composer通过编程化管理和配置插件字段,极大提升了WordPress项目的配置灵活性与开发效率。其简洁的设计和高效的实现,使之成为同类产品中的佼佼者。然而,也要注意其依赖管理对环境要求及可能的安全性问题。对于希望通过编程化管理ACF配置的开发者来说,这无疑是一个强有力的选择。

关于

GitHub 原始描述(英文)

Compose ACF Fields, Blocks, Widgets, and Option Pages with ACF Builder on Sage 10.

描述取自 GitHub 官方 API,保持仓库作者书写的原文。

简要分析

热度分
664
价值分
326
活跃状态
活跃

语言占比

Blade
PHP

Release

README

ACF Composer

Latest Stable Version Total Downloads Build Status

ACF Composer is the ultimate tool for creating fields, blocks, widgets, and option pages using ACF Builder alongside Sage 10 and 11.

Screenshot

Features

  • 🔧 Encourages clean structuring for creating fields with Sage and ACF.
  • 🚀 Instantly generate working fields, blocks, widgets, partials, and option pages using CLI. Batteries included.
  • 🖼️ Fully rendered blocks and widgets using Blade with a native Sage feel for passing view data.
  • ⚡ Seamlessly cache blocks to block.json and field groups to a manifest.
  • 📦 Automatically hooks legacy widgets with WP_Widget making them instantly ready to use.
  • 🛠️ Automatically sets field location on blocks, widgets, and option pages.
  • 🌐 Globally define default field type and field group settings. No more repeating ['ui' => 1] on every select field.

Requirements

Installation

Install via Composer:

$ composer require log1x/acf-composer

Usage

Getting Started

Start by publishing the config/acf.php configuration file using Acorn:

$ wp acorn vendor:publish --tag="acf-composer"

Generating a Field Group

To create your first field group, start by running the following generator command from your theme directory:

$ wp acorn acf:field ExampleField

This will create src/Fields/ExampleField.php which is where you will create and manage your first field group.

Taking a glance at the generated ExampleField.php stub, you will notice that it has a simple list configured.

<?php

namespace App\Fields;

use Log1x\AcfComposer\Builder;
use Log1x\AcfComposer\Field;

class ExampleField extends Field
{
    /**
     * The field group.
     *
     * @return array
     */
    public function fields()
    {
        $fields = Builder::make('example_field');

        $fields
            ->setLocation('post_type', '==', 'post');

        $fields
            ->addRepeater('items')
                ->addText('item')
            ->endRepeater();

        return $fields->build();
    }
}

Proceed by checking the Add Post for the field to ensure things are working as intended.

Field Builder Usage

To assist with development, ACF Composer comes with a usage command that will let you search for registered field types. This will provide basic information about the field type as well as a usage example containing all possible options.

$ wp acorn acf:usage

For additional usage, you may consult the ACF Builder Cheatsheet.

Generating a Field Partial

A field partial consists of a field group that can be re-used and/or added to existing field groups.

To start, let’s generate a partial called ListItems that we can use in the Example field we generated above.

$ wp acorn acf:partial ListItems
<?php

namespace App\Fields\Partials;

use Log1x\AcfComposer\Builder;
use Log1x\AcfComposer\Partial;

class ListItems extends Partial
{
    /**
     * The partial field group.
     *
     * @return array
     */
    public function fields()
    {
        $fields = Builder::make('listItems');

        $fields
            ->addRepeater('items')
                ->addText('item')
            ->endRepeater();

        return $fields;
    }
}

Looking at ListItems.php, you will see out of the box it consists of an identical list repeater as seen in your generated field.

A key difference to note compared to an ordinary field is the omitting of ->build() instead returning the FieldsBuilder instance itself.

This can be utilized in our Example field by passing the ::class constant to ->addPartial():

<?php

namespace App\Fields;

use App\Fields\Partials\ListItems;
use Log1x\AcfComposer\Builder;
use Log1x\AcfComposer\Field;

class Example extends Field
{
    /**
     * The field group.
     *
     * @return array
     */
    public function fields()
    {
        $fields = Builder::make('example');

        $fields
            ->setLocation('post_type', '==', 'post');

        $fields
            ->addPartial(ListItems::class);

        return $fields->build();
    }
}

Generating a Block

Generating a block is generally the same as generating a field as seen above.

Start by creating the block field using Acorn:

$ wp acorn acf:block ExampleBlock
<?php

namespace App\Blocks;

use Log1x\AcfComposer\Block;
use Log1x\AcfComposer\Builder;

class ExampleBlock extends Block
{
    /**
     * The block name.
     *
     * @var string
     */
    public $name = 'Example Block';

    /**
     * The block description.
     *
     * @var string
     */
    public $description = 'Lorem ipsum...';

    /**
     * The block category.
     *
     * @var string
     */
    public $category = 'common';

    /**
     * The block icon.
     *
     * @var string|array
     */
    public $icon = 'star-half';

    /**
     * Data to be passed to the block before rendering.
     *
     * @return array
     */
    public function with()
    {
        return [
            'items' => $this->items(),
        ];
    }

    /**
     * The block field group.
     *
     * @return array
     */
    public function fields()
    {
        $fields = Builder::make('example_block');

        $fields
            ->addRepeater('items')
                ->addText('item')
            ->endRepeater();

        return $fields->build();
    }

    /**
     * Return the items field.
     *
     * @return array
     */
    public function items()
    {
        return get_field('items') ?: [];
    }
}

You may also pass --localize to the command above to generate a block stub with the name and description ready for translation.

$ wp acorn acf:block Example --localize

When running the block generator, one difference to a generic field is an accompanied View is generated in the resources/views/blocks directory.

@if ($items)
  <ul>
    @foreach ($items as $item)
      <li>{{ $item['item'] }}</li>
    @endforeach
  </ul>
@else
  <p>No items found!</p>
@endif

<div>
  <InnerBlocks />
</div>

Like the field generator, the example block contains a simple list repeater and is working out of the box.

Block Preview View

While $block->preview is an option for conditionally modifying your block when shown in the editor, you may also render your block using a seperate view.

Simply duplicate your existing view prefixing it with preview- (e.g. preview-example.blade.php).

Generating a Widget

Important 重要

With WordPress 5.8, Blocks can now be used as widgets making this feature somewhat deprecated as you would just make a block instead.

If you are on the latest WordPress and would like to use the classic widget functionality from ACF Composer, you will need to opt-out of the widget block editor.

Creating a sidebar widget using ACF Composer is extremely easy. Widgets are automatically loaded and rendered with Blade, as well as registered with WP_Widget which is usually rather annoying.

Start by creating a widget using Acorn:

$ wp acorn acf:widget ExampleWidget
<?php

namespace App\Widgets;

use Log1x\AcfComposer\Builder;
use Log1x\AcfComposer\Widget;

class ExampleWidget extends Widget
{
    /**
     * The widget name.
     *
     * @var string
     */
    public $name = 'Example Widget';

    /**
     * The widget description.
     *
     * @var string
     */
    public $description = 'Lorem ipsum...';

    /**
     * Data to be passed to the widget before rendering.
     *
     * @return array
     */
    public function with()
    {
        return [
            'items' => $this->items(),
        ];
    }

    /**
     * The widget title.
     *
     * @return string
     */
    public function title() {
        return get_field('title', $this->widget->id);
    }

    /**
     * The widget field group.
     *
     * @return array
     */
    public function fields()
    {
        $fields = Builder::make('example_widget');

        $fields
            ->addText('title');

        $fields
            ->addRepeater('items')
                ->addText('item')
            ->endRepeater();

        return $fields->build();
    }

    /**
     * Return the items field.
     *
     * @return array
     */
    public function items()
    {
        return get_field('items', $this->widget->id) ?: [];
    }
}

Similar to blocks, widgets are also accompanied by a view generated in resources/views/widgets.

@if ($items)
  <ul>
    @foreach ($items as $item)
      <li>{{ $item['item'] }}</li>
    @endforeach
  </ul>
@else
  <p>No items found!</p>
@endif

Out of the box, the Example widget is ready to go and should appear in the backend.

Generating an Options Page

Creating an options page is similar to creating a regular field group in additional to a few configuration options available to customize the page (most of which, are optional.)

Start by creating an option page using Acorn:

$ wp acorn acf:options ExampleOptions
<?php

namespace App\Options;

use Log1x\AcfComposer\Builder;
use Log1x\AcfComposer\Options as Field;

class ExampleOptions extends Field
{
    /**
     * The option page menu name.
     *
     * @var string
     */
    public $name = 'Example Options';

    /**
     * The option page document title.
     *
     * @var string
     */
    public $title = 'Example Options | Options';

    /**
     * The option page field group.
     *
     * @return array
     */
    public function fields()
    {
        $fields = Builder::make('example_options');

        $fields
            ->addRepeater('items')
                ->addText('item')
            ->endRepeater();

        return $fields->build();
    }
}

Optionally, you may pass --full to the command above to generate a stub that contains additional configuration examples.

$ wp acorn acf:options Options --full

Once finished, you should see an Options page appear in the backend.

All fields registered will have their location automatically set to this page.

Caching Blocks & Fields

As of v3, ACF Composer now has the ability to cache registered blocks to native block.json files and field groups to a flat file JSON manifest automatically using CLI.

This can lead to a dramatic increase in performance in projects both small and large, especially when loading a post in the editor containing multiple custom blocks.

Note 注意

Making changes to blocks or fields once cached will not take effect until cleared or re-cached.

The best time to do this is during deployment and can be done using the acf:cache command:

$ wp acorn acf:cache [--status]

Cache can then be cleared using the acf:clear command:

$ wp acorn acf:clear

The ACF Composer cache status can be found using --status on acf:cache as seen above or by running wp acorn about.

Custom Stub Generation

To customize the stubs generated by ACF Composer, you can easily publish the stubs directory using Acorn:

$ wp acorn acf:stubs

The publish command generates all available stubs by default. However, each stub file is optional. When a stub file doesn’t exist in the stubs/acf-composer directory, the default stub provided by the package will be used.

Default Field Settings

A useful feature unique to ACF Composer is the ability to set field type as well as field group defaults. Any globally set default can of course be over-ridden by simply setting it on the individual field.

Global

Taking a look at config/acf.php, you will see a few pre-configured defaults:

'defaults' => [
    'trueFalse' => ['ui' => 1],
    'select' => ['ui' => 1],
],

When setting trueFalse and select to have their ui set to 1 by default, it is no longer necessary to repeatedly set 'ui' => 1 on your fields. This takes effect globally and can be overridden by simply setting a different value on a field.

Field Group

It is also possible to define defaults on individual field groups. This is done by simply defining $defaults in your field class.

/**
 * Default field type settings.
 *
 * @return array
 */
protected $defaults = ['ui' => 0];

My Defaults

Here are a couple defaults I personally use. Any prefixed with acfe_ are related to ACF Extended.

'defaults' => [
    'fieldGroup' => ['instruction_placement' => 'acfe_instructions_tooltip'],
    'repeater' => ['layout' => 'block', 'acfe_repeater_stylised_button' => 1],
    'trueFalse' => ['ui' => 1],
    'select' => ['ui' => 1],
    'postObject' => ['ui' => 1, 'return_format' => 'object'],
    'accordion' => ['multi_expand' => 1],
    'group' => ['layout' => 'table', 'acfe_group_modal' => 1],
    'tab' => ['placement' => 'left'],
    'sidebar_selector' => ['default_value' => 'sidebar-primary', 'allow_null' => 1]
],

Bug Reports

If you discover a bug in ACF Composer, please open an issue.

Contributing

Contributing whether it be through PRs, reporting an issue, or suggesting an idea is encouraged and appreciated.

License

ACF Composer is provided under the MIT License.

评论

暂无评论