sfneal / view-models
spatie/view-models wrapper with built in response caching.
Installs: 73 974
Dependents: 2
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 1
Requires
- php: ^8.0|^8.1|^8.2|^8.3
- sfneal/caching: ^2.0|^3.0|^4.0
- sfneal/laravel-helpers: ^2.4
- sfneal/queueables: ^2.0
- sfneal/redis-helpers: ^1.2|^2.0|^3.0
- sfneal/string-helpers: ^1.0
- spatie/laravel-view-models: ^1.1
Requires (Dev)
- ext-json: *
- josiasmontag/laravel-redis-mock: >=1.2.6
- orchestra/testbench: ^7.40|^8.0|9.0
- phpunit/phpunit: ^9.6|^10.0|^11.0
- scrutinizer/ocular: ^1.8
README
spatie/view-models wrapper with built in response caching
Installation
You can install the package via composer:
composer require sfneal/view-models
Usage
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(); } }
Testing
composer test
Changelog
Please see CHANGELOG for more information what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email stephen.neal14@gmail.com instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.
PHP Package Boilerplate
This package was generated using the PHP Package Boilerplate.