rareloop/view-models

一个小型包,使处理视图变得更加容易

v1.0.1 2017-07-07 15:08 UTC

This package is auto-updated.

Last update: 2024-09-12 05:01:28 UTC


README

此包已弃用。视图模型现在已集成到 Lumberjack 核心。

视图模型

在这里,ViewModel 指的是一种从数据中提取信息并将其转换为特定视图正确格式的实体。它们是 输入-输出机器

例如,对于这个 twig 视图

{% for link in links %}
    <a href="{{ link.url }}">{{ link.title }}</a>
{% endfor %}

您需要构建一个类似这样的数组(例如在控制器中)

// Get pages from the database somehow
$pages = Page::all();

$data = ['links' => []];

foreach ($pages as $page) {
    // Map the page to the correct structure for the view
    $data['links'][] = [
        'url' => $page->permalink,
        'title' => $page->post_title,
    ];
}

** 视图模型抽象化了这种转换。这意味着您不需要在多个控制器中重复该转换逻辑,从而使您的代码更容易更改。**

后卡商品

您可以使用此包(它是MIT许可的),但如果它进入了您的生产环境,我们非常希望您从家乡寄给我们一张明信片,说明您正在使用我们的哪个包。

我们的地址是:12 Basepoint, Andersons Road, Southampton, Hampshire, SO14 5FE。

安装

您可以通过 composer 安装此包

composer require rareloop/view-models

视图模型使用

它们应该始终返回一个数组。实现这一点最简单的方法是在视图模型上运行数据通过 compose 方法。

它们不应该从任何地方获取数据(例如数据库)。这是 ViewModelComposer 的职责。

使用示例 ViewModel(例如在控制器中)

$params = new ParameterBag([
    'links' => [
        'https://google.com',
        'https://rareloop.com',
    ],
]);

$context['links'] = \App\ViewModels\Links::make($params);

这是一个 ViewModel 实现示例

namespace App\ViewModels\Links;

use Rareloop\ViewModels\ParameterBag;
use Rareloop\ViewModels\ViewModel;

class Links extends ViewModel
{
    public static function make(ParameterBag $params): array
    {
        // Transform the data into the correct structure
        $data = array_map(function ($item) {
            return [
                'url' => $item['ID'],
            ];
        }, $params->links);

        // Make sure the data is an array
        return static::compose($data);
    }
}

介绍视图模型组合器

ViewModelComposerViewModel 的一个包装器,但它只关注如何为 ViewModel 准备数据。

这些应该在创建 ViewModel 时替代重复的逻辑(例如在控制器中)。

示例 ViewModelComposer 实现

class RelatedLinks
{
    public static function make(): array
    {
        // e.g. you could get the data out of the database for the related links for this page
        $args = new ParameterBag([
            'links' => [
                'http://google.com',
                'https://rareloop.com',
            ],
        ]);

        return Links::make($args);
    }
}

更新日志

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

测试

composer test

贡献

请参阅贡献指南以获取详细信息。

安全性

如果您发现任何安全相关的问题,请通过电子邮件info@rareloop.com联系,而不是使用问题跟踪器。

许可

MIT 许可(MIT)。有关更多信息,请参阅许可文件