Spiral 框架的 Livewire 集成桥梁

1.x-dev 2024-04-16 17:09 UTC

This package is auto-updated.

Last update: 2024-09-16 17:57:40 UTC


README

PHP Version Require Latest Stable Version phpunit psalm Codecov Total Downloads type-coverage psalm-level

警告!

该软件包目前正在积极开发中。由于其可能的不稳定性,不建议在生产环境中使用。

需求

请确保您的服务器已配置以下 PHP 版本和扩展

  • PHP 8.1+
  • Spiral 框架 3.7+

安装

您可以通过 composer 安装此软件包

composer require spiral-packages/livewire

要启用 Spiral 框架应用程序中的软件包,您需要将 Spiral\Livewire\Bootloader\LivewireBootloader 类添加到应用程序的引导程序列表中

protected const LOAD = [
    // ...
    \Spiral\Livewire\Bootloader\LivewireBootloader::class,
];

注意 如果您正在使用 spiral-packages/discoverer,则无需自行注册引导程序。

模板引擎

Twig

要在 Spiral 框架应用程序中开始使用 LivewireTwig,需要将 Spiral\Livewire\Bootloader\TwigBootloader 类添加到应用程序的引导程序列表中。

以下是一个示例

    // ...
    \Spiral\Livewire\Bootloader\TwigBootloader::class,

当注册 TwigBootloader 时,它提供了 Spiral\Livewire\Twig\Extension\LivewireExtension 扩展,允许使用 livewire_styleslivewire_scriptslivewire Twig 函数。

  • livewire_styleslivewire_scripts - 这些函数用于包含所需的 Livewire CSS 和 JavaScript 代码。
  • livewire - 此函数将组件的 name 作为第一个参数,并渲染组件的初始状态。后续参数将传递给组件的 mount 方法。

Stempler

要在 Spiral 框架应用程序中开始使用 LivewireStempler,需要将 Spiral\Livewire\Bootloader\StemplerBootloader 类添加到应用程序的引导程序列表中。

以下是一个示例

    // ...
    \Spiral\Livewire\Bootloader\StemplerBootloader::class,

当注册 StemplerBootloader 时,它提供了 Spiral\Livewire\Template\Stempler\LivewireDirective 指令,允许使用 livewireStyleslivewireScripts 指令,以及 Spiral\Livewire\Template\Stempler\NodeVisitor,它可以使用 <livewire:name /> 标签语法在页面上渲染 Livewire 组件。

  • livewireStyleslivewireScripts - 这些函数用于包含所需的 Livewire CSS 和 JavaScript 代码。

配置

配置文件应位于 app/config/livewire.php,它允许您设置选项。以下是一个配置文件示例

use Spiral\Events\Config\EventListener;
use Spiral\Livewire\Component\Registry\Processor\AttributeProcessor;
use Spiral\Livewire\Event\Component\ComponentHydrateSubsequent;
use Spiral\Livewire\Listener\Component\SupportChildren;
use Spiral\Livewire\Listener\Component\SupportLocales;
use Spiral\Livewire\Middleware\Component\CallHydrationHooks;
use Spiral\Livewire\Middleware\Component\CallPropertyHydrationHooks;
use Spiral\Livewire\Middleware\Component\HydrateModelProperties;
use Spiral\Livewire\Interceptor\Mount\CycleInterceptor;
use Spiral\Livewire\Interceptor\Mount\TypecasterInterceptor;

return [
    'listeners' => [
        // ...
        ComponentHydrateSubsequent::class => [
            new EventListener(
                listener: SupportLocales::class,
                method: 'onComponentHydrateSubsequent',
                priority: 10
            ),
            new EventListener(
                listener: SupportChildren::class,
                method: 'onComponentHydrateSubsequent',
                priority: 20
            ),
        ],
        // ...
    ],
    'interceptors' => [
        'mount' => [
            CycleInterceptor::class,
            TypecasterInterceptor::class,
        ],
        'boot' => []
    ],
    'initial_hydration_middleware' => [
        // ...
        CallHydrationHooks::class,
        // ...
    ],
    'hydration_middleware' => [
        // ...
        HydrateModelProperties::class,
        // ...
    ],
    'initial_dehydration_middleware' => [
        // ...
        CallPropertyHydrationHooks::class,
        // ...
    ],
    'dehydration_middleware' => [
        // ...
        CallPropertyHydrationHooks::class,
        // ...
    ],
    'processors' => [
        // ...
        AttributeProcessor::class,
        // ...
    ],
    'disable_browser_cache' => true,
];

注意 该软件包默认已配置,无需任何其他配置。仅在需要更改默认配置时使用配置文件。

警告 所有中间件顺序都很重要!正确的顺序可以在默认配置中查看:src/Bootloader/ConfigBootloader.php

使用方法

添加所需的 Livewire CSS 和 JavaScript 代码

Twig

<!DOCTYPE html>
<html lang="@{locale}">
    <head>
        // ...
        {{ livewire_styles() }}
    </head>
    <body>
        {% block body %}{% endblock %}
        {{ livewire_scripts() }}
    </body>
</html>

Stempler

<!DOCTYPE html>
<html lang="@{locale}">
<head>
    // ...
    @livewireStyles
</head>
<body>
    // ...
    @livewireScripts
</body>
</html>

让我们创建一个简单的 Livewire 组件 Counter

namespace App\Endpoint\Web\Livewire\Component;

use Spiral\Livewire\Attribute\Component;
use Spiral\Livewire\Attribute\Model;
use Spiral\Livewire\Component\LivewireComponent;

#[Component(name: 'counter', template: 'components/counter')]
final class Counter extends LivewireComponent
{
    #[Model]
    public int $count = 0;

    public function increment(): void
    {
        $this->count++;
    }
}

创建模板

<div style="text-align: center">
    <button wire:click="increment">+</button>
    <h1>{{ count }}</h1>
</div>

在模板的任何位置调用 Livewire 组件。

Twig

{{ livewire('counter') }}

Stempler

<livewire:counter />

现在在浏览器中重新加载页面,您应该看到渲染的计数器组件。如果您点击“+”按钮,页面应该会自动更新而无需重新加载页面。

验证

启用 Livewire 组件中验证的第一步是确保已安装并正确配置了 spiral\validatorspiral-packages/laravel-validator 软件包。一旦确保验证软件包已安装,您需要将 Spiral\Livewire\Bootloader\ValidationBootloader 类添加到应用程序的引导程序列表中

protected const LOAD = [
    // ...
    \Spiral\Livewire\Bootloader\ValidationBootloader::class,
];

在添加了ValidationBootloader类之后,您必须在您的Livewire组件中实现Spiral\Livewire\Validation\ShouldBeValidated接口,并定义validationRules方法来指定您的验证规则。此方法应返回一个数组,包含每个需要验证的属性验证规则。验证规则必须符合您使用的验证器支持的格式。

注意 验证规则在Spiral ValidatorLaravel Validator文档中描述。

例如,如果您想验证ContactForm组件的nameemail字段,可以像这样定义组件。

Spiral Validator

namespace App\Endpoint\Web\Livewire\Component;

use Spiral\Livewire\Attribute\Component;
use Spiral\Livewire\Attribute\Model;
use Spiral\Livewire\Component\LivewireComponent;
use Spiral\Livewire\Validation\ShouldBeValidated;

#[Component(name: 'contact-form', template: 'components/contact-form.twig')]
final class ContactForm extends LivewireComponent implements ShouldBeValidated
{
    #[Model]
    public string $name;

    #[Model]
    public string $email;

    public function submit(): void
    {
        // This method will only be called if all the data is valid
    }

    public function validationRules(): array
    {
        return [
            'name' => ['required'],
            'email' => ['required', 'email']
        ];
    }

Laravel Validator

namespace App\Endpoint\Web\Livewire\Component;

use Spiral\Livewire\Attribute\Component;
use Spiral\Livewire\Attribute\Model;
use Spiral\Livewire\Component\LivewireComponent;
use Spiral\Livewire\Validation\ShouldBeValidated;

#[Component(name: 'contact-form', template: 'components/contact-form.twig')]
final class ContactForm extends LivewireComponent implements ShouldBeValidated
{
    #[Model]
    public string $name;

    #[Model]
    public string $email;

    public function submit(): void
    {
        // This method will only be called if all the data is valid
    }

    public function validationRules(): array
    {
        return [
            'name' => 'required',
            'email' => 'required|email'
        ];
    }

在这些示例中,validationRules方法返回一个规则数组,指定名称和电子邮件字段都是必填字段,并且电子邮件字段必须是有效的电子邮件地址。

  • 当属性更新时,验证器只能验证单个属性。如果组件配置为在字段更改时更新数据。例如,验证器可能会在用户点击提交按钮之前验证电子邮件并显示错误。
  • 在调用组件方法之前,验证器会检查所有数据,只有当所有数据有效时才会调用该方法。

拦截器

Spiral通过拦截器提供了一种方式,允许开发者在执行bootmount方法之前或之后自定义其行为。拦截器是一段代码,在调用mount或boot方法之前或之后执行。

一些拦截器由包提供并默认启用。

  • Spiral\Livewire\Interceptor\Mount\CycleInterceptor - 这是一个mount拦截器。根据给定的参数自动解析Cycle实体。
  • Spiral\Livewire\Interceptor\Mount\TypecasterInterceptor - 这是一个mount拦截器。自动将传递给mount方法的参数转换为所需类型(boolintfloatarray)。

注意 CycleInterceptor需要Cycle ORM Bridge。如果您不使用它,拦截器将不会激活。

您可以创建自己的拦截器并将其注册到配置文件中。

namespace App\Interceptor;

use Spiral\Core\CoreInterceptorInterface;
use Spiral\Core\CoreInterface;
use Spiral\Livewire\Component\LivewireComponent;

class SomeInterceptor implements CoreInterceptorInterface
{
    /**
     * @param class-string $controller Component class name
     * @param string $action method (boot or mount)
     * @param array{
     *     component: LivewireComponent,
     *     reflection: \ReflectionMethod,
     *     parameters: array
     * } $parameters Array with additional parameters.
     *  For the mount method, contains an array with the parameters that were passed to it.
     */
    public function process(string $controller, string $action, array $parameters, CoreInterface $core): mixed
    {
        // Some code before calling method mount or boot

        $core->callAction($controller, $action, $parameters);

        // Some code after calling method mount or boot

        return null;
    }
}
// file app/config/livewire.php
use App\Interceptor\SomeInterceptor;
use Spiral\Livewire\Interceptor\Mount\CycleInterceptor;
use Spiral\Livewire\Interceptor\Mount\TypecasterInterceptor;

return [
    'interceptors' => [
        'mount' => [
            SomeInterceptor::class,
            CycleInterceptor::class,
            TypecasterInterceptor::class,
        ],
        'boot' => [
            SomeInterceptor::class,
        ]
    ],
];

测试

composer test
composer psalm
composer cs

更新日志

请参阅更新日志以获取有关最近更改的更多信息。

许可

MIT许可证(MIT)。请参阅许可文件以获取更多信息。