8xprovn/widgets

dev-main 2023-09-06 14:57 UTC

This package is auto-updated.

Last update: 2024-09-06 17:04:12 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 命名空间中查找您的 widget。

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

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

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

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

异步小部件

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

幸运的是,这可以很容易地实现!您需要做的只是更改 facade 或 blade 指令 - Widget:: > AsyncWidget::@widget > @asyncWidget

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

注意:您可以通过在它上面设置 public $encryptParams = false; 来关闭特定小部件的加密。然而,这个操作会使小部件参数公开访问,所以请确保不要留下任何漏洞。例如,如果您通过小部件参数传递类似 user_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 调用垃圾邮件式地占用您的应用程序。考虑使用 WebSocket,但这要难设置得多。

容器

异步和可重新加载的小部件都需要一些 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(); // 布尔值

Widget::group('sidebar')->any(); // 布尔值

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

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

在某些情况下,将小部件与您自己的包一起提供可能很有用。例如,如果您的包允许您管理新闻,那么方便地立即可配置的、可直接与您的包一起提供用于显示的小部件将非常有用。

为了避免每次都使用 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')