wuwx/laravel-widgets

视图构建器的强大替代品。异步小部件,可重载小部件,控制台生成器,缓存——你想得到的都有。

3.13.0 2019-03-25 14:20 UTC

README

Latest Stable Version Total Downloads Build Status Scrutinizer Quality Score

Laravel 小部件

视图构建器的强大替代品。异步小部件,可重载小部件,控制台生成器,缓存——你所能想象到的。

安装

运行 composer require wuwx/laravel-widgets:dev-master

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);
}

直接

您也可以选择直接向 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 属性来覆盖此。

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

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

  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; 设置在 widget 上来关闭特定 widget 的加密。但是,此操作将使 widget 参数公开访问,因此请确保不要留下任何漏洞。例如,如果您通过 widget 参数传递 user_id 并关闭加密,您确实需要在 widget 内部添加一个额外的访问检查。

注意:您可以在配置文件中将 use_jquery_for_ajax_calls 设置为 true 以在需要时使用它进行 ajax 调用。

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

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

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

旁白:如果您需要使用用于加载异步 widget 的路由包进行某些操作(例如,您在子文件夹中运行应用程序 http://site.com/app/),则需要将 Arrilot\Widgets\ServiceProvider 复制到您的应用程序中,根据您的需求进行修改,并在 Laravel 中注册它而不是之前的版本。

可重新加载的 widget

您甚至可以更进一步,每 N 秒自动重新加载 widget。

只需设置 widget 类的 $reloadTimeout 属性即可完成。

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

同步和异步 widget 都可以变为可重新加载。

您应该谨慎使用此功能,因为如果超时时间太短,它很容易使您的应用程序充满 ajax 调用。考虑使用 WebSocket,但它们设置起来要困难得多。

容器

异步和可重新加载的 widget 都需要一些 DOM 交互,因此它们将所有 widget 输出包装在一个 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"',
    ];
}

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

缓存

还有一个简单内置的方式来缓存整个 widget 输出。只需在您的 widget 类中设置 $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;
}

默认情况下,未启用缓存。缓存键依赖于 widget 名称和每个 widget 参数。如果需要调整,请覆盖 cacheKey 方法。

缓存标签

当支持标签(请参阅 Laravel 缓存文档 https://laravel.net.cn/docs/cache#cache-tags)并且为了简化缓存清理时,默认将标签 widgets 分配给所有 widget。您可以在您的 widget 类中设置 $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();

Widget 组(额外)

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

// 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 之间显示的分隔符设置一个分隔符。 Widget::group('sidebar')->setSeparator('<hr>')->...;

您还可以使用 wrap 方法将每个 widget 包装在组中。

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>";
})->...;

从组中删除 widget

在 widget 已经被添加到组之后,有几种方法可以删除 widget。

  1. 通过其唯一的 id 删除一个 widget
$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
Widget::group('sidebar')->addWidget('files');
Widget::group('sidebar')->addAsyncWidget('files');
Widget::group('sidebar')->removeByName('files'); // Widget group is empty now
  1. 删除放置在特定位置的所有 widget。
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。
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

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

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

为了避免每次都必须使用 fqcn,您可以在您的包提供者中设置 widget 命名空间。这样,您的包中的 widget 可以更容易地识别,并且语法会更短。

为此,您只需在您的包服务提供程序中注册命名空间即可

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')