takemo101 / laravel-simple-vm
Laravel Simple VM
v0.1.3
2022-03-19 06:30 UTC
Requires
- php: ^8.0
- illuminate/console: ^8|^9
- illuminate/filesystem: ^8|^9
- illuminate/support: ^8|^9
- takemo101/simple-vm: ^0.1.4
Requires (Dev)
- php: ^8.0
- orchestra/testbench: ^7.0
- phpstan/phpstan: ^1.4
- phpunit/phpunit: ^9.5
README
此包是对 Laravel 的 Simple VM 的封装。
您还可以使用命令创建 ViewModel 类。
祝您使用愉快!
安装
执行以下 composer 命令。
composer require takemo101/laravel-simple-vm
使用方法
请按照以下步骤使用
创建 ViewModel 类
执行以下 artisan 命令。
# php artisan make:svm TestViewModel
基础
1. 创建 ViewModel 类
首先,创建一个 ViewModel 类,用于将数据输出到视图。
<?php namespace App\Http\ViewModel; use Takemo101\LaravelSimpleVM\ViewModel; use Takemo101\SimpleVM\Attribute\{ Ignore, ChangeName, }; use App\Models\User; use Illuminate\Support\Collection; /** * You need to extend and create the ViewModel class. * Only the public properties and methods defined in the ViewModel class will be the output target values. */ class TestViewModel extends ViewModel { /** * ignores property or method names * * @var string[] */ protected array $__ignores = [ // ]; /** * The data to be output to View is passed to the ViewModel class in the constructor. */ public function __construct( public string $description, private User $user, ) { // } /** * Method injection is available for each published method */ public function users(User $user): Collection { return $user->all(); } /** * You can also process the model object and output it like the JsonResponse class. */ public function user(): array { return [ 'name' => $this->user->name, 'email' => $this->user->email, ]; } /** * You can ignore the output to the View by setting the Ignore Attribute class */ #[Ignore] public function other(): string { return 'other'; } /** * You can change the output name to the View by setting the ChangeName Attribute class. */ #[ChangeName('modification')] public function change(): string { return 'change'; } }
2. 在控制器类中使用 ViewModel 类
接下来,在控制器中将创建的 ViewModel 类对象作为响应使用。
<?php namespace App\Http\Controllers; use App\Http\ViewModel\TestViewModel; use App\Models\User; class HomeController { /** * Output Json by making the return value of the controller method an object of ViewModel */ public function json() { $user = new User(); $user->name = 'name'; $user->email = 'xxx@xxx.com'; return new TestViewModel( 'description', $user, ); } /** * You can use the output data on the template by passing a ViewModel object as the template data */ public function view() { $user = new User(); $user->name = 'name'; $user->email = 'xxx@xxx.com'; // By using the toAccessArray method, you can treat the output data like an object on the template. return view('home.view', (new TestViewModel( 'description', $user, ))->toAccessArray()); // You can create an object from the of method of the ViewModel class } }
以下是在 Json 格式中的输出结果。
{ "description": "description", "users": [], "user": { "name": "name", "email": "xxx@xxx.com" }, "modification": "change" }