casperw/laravel-view-model-adaptor

简化视图模型类使用的视图模型适配器。

v1 2018-11-02 11:52 UTC

This package is auto-updated.

Last update: 2020-02-12 12:52:25 UTC


README

Latest Version on Packagist Total Downloads Software License

Laravel ViewModel Adaptor

这个简单的包提供了一个视图模型适配器,您可以使用它来渲染视图模型。

安装

通过Composer

$ composer require casperw/laravel-view-model-adaptor

将服务提供者添加到您的/config/app.php

CasperW\LaravelViewModelAdaptor\LaravelViewModelAdaptorServiceProvider::class

使用

步骤 1

创建一个实现包的ViewModelInterface的view-model

    class DashboardViewModel implements ViewModelInterface
    {
        private $transactions;

        public function load ($data) : ViewModelInterface
        {
            $this->transactions = $data;
    
            return $this;
        }

        public function getTransactions () : Collection
        {
            return $this->transactions;
        }

        public function getTotalCredit () : float
        {
            return $this->transactions->where('amount', '>', 0)->sum('amount');
        }
    }

步骤 2

接下来,在控制器的构造函数中添加view-model apdaptor interface

    class DashboardController extends Controller
    {
        protected $view_model_adaptor;
    
        public function __construct (ViewModelAdaptorInterface $view_model_adaptor)
        {
            $this->view_model_adaptor = $view_model_adaptor;
        }
    }

步骤 3

最后,使用load方法来渲染视图模型。

    public function index ()
    {
        $dashboard_view_model = $this->view_model_adaptor->load(
            Transaction::all(), 
            DashboardViewModel::class
        );

        return view('transactions', [
            'dashboard_view_model' => $dashboard_view_model,
        ]);
    }

您还可以将一个interface作为第二个参数插入。这使您可以在视图模型中实现依赖注入。

    public function index ()
    {
        $dashboard_view_model = $this->view_model_adaptor->load(
            Transaction::all(), 
            DashboardViewModelInterface::class
        );

        return view('transactions', [
            'dashboard_view_model' => $dashboard_view_model,
        ]);
    }

许可证

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