casperw/laravel-view-model-adaptor

A view model adaptor to simplify the use of view model classes.

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

This simple package gives a view model adaptor which you can then use to render view models with.

Installation

Via Composer

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

Add the service provider to your /config/app.php

CasperW\LaravelViewModelAdaptor\LaravelViewModelAdaptorServiceProvider::class

Usage

Step 1

Create a view-model that implements the package's ViewModelInterface.

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

Step 2

Next, add the view-model apdaptor interface in your controller's constructor..

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

Step 3

And finally, use the load method, to render the view model.

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

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

It's also possible to insert an interface as a second parameter. This enables dependency injection in your view-model.

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

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

License

MIT. Please see the license file for more information.