spatie/view-models wrapper with built in response caching
MIT License
spatie/view-models wrapper with built in response caching
You can install the package via composer:
composer require sfneal/view-models
A view model is a class where you can put some complex logic for your views. This will make your controllers a bit lighter. You can create a view model by extending the provided Sfneal\ViewModels\AbstractViewModel.
use Sfneal\ViewModels\ViewModel;
class PostViewModel extends ViewModel
{
public $indexUrl = null;
public function __construct(User $user, Post $post = null)
{
$this->user = $user;
$this->post = $post;
$this->indexUrl = action([PostsController::class, 'index']);
$this->view = 'your.view';
}
public function post(): Post
{
return $this->post ?? new Post();
}
public function categories(): Collection
{
return Category::canBeUsedBy($this->user)->get();
}
}
And used in controllers like so:
class PostsController
{
public function create()
{
// Uses caching for fast load times after first request
return (new PostViewModel(current_user()))->render();
}
public function edit(Post $post)
{
// Doesn't use caching to avoid need for cache invalidation on changes
return (new PostViewModel(current_user(), $post))->renderNoCache();
}
}
composer test
Please see CHANGELOG for more information what has changed recently.
Please see CONTRIBUTING for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.
This package was generated using the PHP Package Boilerplate.