iohttp/laravel-widgets

视图组件的强大替代品。异步组件,可重载组件,控制台生成器,缓存——你想得到的一切。

1.0.2 2022-12-10 18:08 UTC

This package is auto-updated.

Last update: 2024-09-10 22:11:26 UTC


README

Latest Stable Version Total Downloads Build Status Scrutinizer Quality Score

Laravel 组件

视图组件的强大替代品。异步组件,可重载组件,控制台生成器,缓存——你能想象的一切。

安装

运行 composer require arrilot/laravel-widgets

Laravel >=5.5 使用包自动发现,因此您不需要手动添加 ServiceProvider 和 Facades

使用方法

让我们假设我们想要创建一个最近的新闻列表,并在多个视图中重用它。

首先,我们可以使用包提供的 artisan 命令创建一个 Widget 类。

php artisan make:widget RecentNews

此命令生成两个文件

  1. resources/views/widgets/recent_news.blade.php 是一个空的视图。

如果您不需要视图,请添加 "--plain" 选项。

  1. app/Widgets/RecentNews 是一个组件类。
<?php

namespace App\Widgets;

use Arrilot\Widgets\AbstractWidget;

class RecentNews extends AbstractWidget
{
    /**
     * The configuration array.
     *
     * @var array
     */
    protected $config = [];

    /**
     * Treat this method as a controller action.
     * Return view() or other content to display.
     */
    public function run()
    {
        //

        return view('widgets.recent_news', [
            'config' => $this->config,
        ]);
    }
}

注意:如果您需要,可以使用自己的模板。发布配置文件以更改路径。

最后一步是调用组件。有几种方法可以这样做。

@widget('recentNews')

{{ Widget::run('recentNews') }}

或者甚至

{{ Widget::recentNews() }}

这些之间没有真正的区别。选择权在你。

向组件传递变量

通过配置数组

让我们继续“最近新闻”的例子。

想象一下,我们通常需要显示 五个 新闻,但在某些视图中我们需要显示 十个。这可以通过以下方式轻松实现:

class RecentNews extends AbstractWidget
{
    ...
    protected $config = [
        'count' => 5
    ];
    ...
}

...
@widget('recentNews') // shows 5
@widget('recentNews', ['count' => 10]) // shows 10

['count' => 10] 是一个配置数组,可以通过 $this->config 访问。

配置数组在每个组件方法中都可用,因此您可以使用它来配置占位符和容器(见下文)

注意:在调用组件时未指定的配置字段不会被覆盖

class RecentNews extends AbstractWidget
{
    ...
    protected $config = [
        'count' => 5,
        'foo'   => 'bar'
    ];
    
    ...
}

@widget('recentNews', ['count' => 10]) // $this->config['foo'] is still 'bar'

注意 2:您可能想(但可能不需要)创建自己的 BaseWidget 并从中继承。这没问题。唯一的边缘情况是从父类和子类合并配置默认值。在这种情况下,请执行以下操作

  1. 不要向子类中添加 protected $config = [...] 行。

  2. 相反,添加默认值如下

public function __construct(array $config = [])
{
    $this->addConfigDefaults([
        'child_key' => 'bar'
    ]);

    parent::__construct($config);
}

直接(仅适用于 Laravel 版本低于 7)

您还可以选择直接向 run() 方法传递额外的参数。

@widget('recentNews', ['count' => 10], 'date', 'asc')
...
public function run($sortBy, $sortOrder) { }
...

run() 方法是通过服务容器解析的,因此这里也可以使用方法注入。

命名空间

默认情况下,包试图在 App\Widgets 命名空间中找到您的组件。

您可以通过发布包配置(php artisan vendor:publish --provider="Arrilot\Widgets\ServiceProvider")并设置 default_namespace 属性来覆盖此设置。

虽然使用默认命名空间非常方便,但在某些情况下,您可能希望有更多的灵活性。例如,如果您有数十个组件,将它们分组在命名空间文件夹中是有意义的。

没问题,有几种方法可以调用这些组件

  1. default_namespace 的完整组件名称(基本上是 App\Widgets)传递给 run 方法。
@widget('News\RecentNews', $config)
  1. 使用点表示法。
@widget('news.recentNews', $config)
  1. FQCN 也是一个选项。
@widget('\App\Http\Some\Namespace\Widget', $config)

异步组件

在某些情况下,使用 AJAX 加载组件内容可以非常有用。

幸运的是,这可以非常容易地实现!您需要做的就是更改外观或 blade 指示符 - Widget:: => AsyncWidget::@widget => @asyncWidget

组件参数默认情况下是加密的,并在底层通过 AJAX 调用发送。因此,请预期它们在之后会被 json_encoded()json_decoded()

注意:您可以通过将 public $encryptParams = false; 设置在特定的部件上来关闭其加密。然而,这个操作会使部件参数对公众可访问,所以请确保不要留下任何漏洞。例如,如果您通过部件参数传递用户ID并关闭加密,您确实需要在部件内添加一个额外的访问检查。

注意:您可以在配置文件中将 use_jquery_for_ajax_calls 设置为 true 以使用它进行ajax调用,但在此情况下您需要手动将jquery添加到您的页面上。

默认情况下,直到ajax调用完成之前不显示任何内容。

您可以通过向部件类添加一个 placeholder() 方法来自定义此内容。

public function placeholder()
{
    return 'Loading...';
}

边注:如果您需要处理用于加载异步部件的路线包(例如,您在一个子目录中运行应用 http://site.com/app/),您需要将 Arrilot\Widgets\ServiceProvider 复制到您的应用中,根据您的需要进行修改,并在Laravel中注册它,而不是使用之前的版本。

可重新加载的部件

您可以更进一步,并自动每N秒重新加载部件。

只需设置部件类的 $reloadTimeout 属性即可。

class RecentNews extends AbstractWidget
{
    /**
     * The number of seconds before each reload.
     *
     * @var int|float
     */
    public $reloadTimeout = 10;
}

同步和异步部件都可以成为可重新加载的。

您应该小心使用此功能,因为如果超时时间太低,它可能会轻易地通过ajax调用使您的应用变得垃圾。同时考虑使用web sockets,但它们设置起来要困难得多。

容器

异步和可重新加载的部件都需要一些DOM交互,因此它们将所有部件输出包装在一个HTML容器中。此容器由 AbstractWidget::container() 方法定义,也可以进行自定义。

/**
 * Async and reloadable widgets are wrapped in container.
 * You can customize it by overriding this method.
 *
 * @return array
 */
public function container()
{
    return [
        'element'       => 'div',
        'attributes'    => 'style="display:inline" class="arrilot-widget-container"',
    ];
}

注意:不支持嵌套异步或可重新加载的部件。

缓存

还有一个简单内置的方式来缓存整个部件输出。只需在您的部件类中设置 $cacheTime 属性即可。

class RecentNews extends AbstractWidget
{
    /**
     * The number of minutes before cache expires.
     * False means no caching at all.
     *
     * @var int|float|bool
     */
    public $cacheTime = 60;
}

默认情况下没有开启缓存。缓存键取决于部件名称以及每个部件参数。如果您需要调整它,请覆盖 cacheKey 方法。

缓存标记

当支持标记(参见Laravel缓存文档)并且为了简化缓存刷新时,默认将 widgets 标签分配给所有部件。您可以通过在您的部件类中设置 $cacheTags 属性来为您的部件定义一个或多个额外的标签。示例

class RecentNews extends AbstractWidget
{
    /**
     * Cache tags allow you to tag related items in the cache 
     * and then flush all cached values that assigned a given tag.
     *
     * @var array
     */
    public $cacheTags = ['news', 'frontend'];
}

对于此示例,如果您需要刷新

// Clear widgets with the tag news
Cache::tags('news')->flush();

// Clear widgets with the tag news OR backend
Cache::tags(['news', 'frontend'])->flush();

// Flush all widgets cache
Cache::tags('widgets')->flush();

部件组(额外功能)

在大多数情况下,Blade 是设置部件位置和顺序的完美工具。然而,有时您可能会发现以下方法很有用

// add several widgets to the 'sidebar' group anywhere you want (even in controller)
Widget::group('sidebar')->position(5)->addWidget('widgetName1', $config1);
Widget::group('sidebar')->position(4)->addAsyncWidget('widgetName2', $config2);

// display them in a view in the correct order
@widgetGroup('sidebar')
// or 
{{ Widget::group('sidebar')->display() }}

可以省略链中的 position()

Widget::group('sidebar')->addWidget('files');

等于

Widget::group('sidebar')->position(100)->addWidget('files');

您可以为组中的部件之间显示的分隔符设置一个。 Widget::group('sidebar')->setSeparator('<hr>')->...;

您也可以使用 wrap 方法将组中的每个部件包裹起来。

Widget::group('sidebar')->wrap(function ($content, $index, $total) {
    // $total is a total number of widgets in a group.
    return "<div class='widget-{$index}'>{$content}</div>";
})->...;

从组中移除部件

有几种方法可以在部件已添加到组中之后从组中移除部件/部件。

  1. 通过其唯一的 id 移除一个部件
$id1 = Widget::group('sidebar')->addWidget('files');
$id2 = Widget::group('sidebar')->addAsyncWidget('files');
Widget::group('sidebar')->removeById($id1); // There is only second widget in the group now
  1. 移除所有具有特定名称的部件
Widget::group('sidebar')->addWidget('files');
Widget::group('sidebar')->addAsyncWidget('files');
Widget::group('sidebar')->removeByName('files'); // Widget group is empty now
  1. 移除放置在特定位置的所有部件。
Widget::group('sidebar')->position(42)->addWidget('files');
Widget::group('sidebar')->position(42)->addAsyncWidget('files');
Widget::group('sidebar')->removeByPosition(42); // Widget group is empty now
  1. 一次性移除所有部件。
Widget::group('sidebar')->addWidget('files');
Widget::group('sidebar')->addAsyncWidget('files');
Widget::group('sidebar')->removeAll(); // Widget group is empty now

检查组的状况

Widget::group('sidebar')->isEmpty(); // bool

Widget::group('sidebar')->any(); // bool

Widget::group('sidebar')->count(); // int

第三方包的命名空间(额外功能)

在某些情况下,使用自己的包来交付小部件可能很有用。例如,如果您的包允许您管理新闻,那么拥有可以立即配置、准备显示的小部件并将它们直接与您的包一起交付将会很方便。

为了避免每次都要使用完全限定类名(fqcn),您可以在您的包提供者中设置一个小部件命名空间。这样,您包中的小部件可以更容易地被识别,特别是语法将会更简短。

要做到这一点,您只需在您的包服务提供者中注册命名空间即可。

public function boot() 
{
    app('arrilot.widget-namespaces')->registerNamespace('my-package-name', '\VendorName\PackageName\Path\To\Widgets');
}

之后,您就可以在您的视图中使用该命名空间。

@widget('my-package-name::foo.bar')

// is equivalent to
@widget('\VendorName\PackageName\Path\To\Widgets\Foo\Bar')