spatie / laravel-view-models

View models in Laravel
https://spatie.be/open-source
MIT License
1.02k stars 61 forks source link

[Support] How to reuse view model #25

Closed phuclh closed 4 years ago

phuclh commented 4 years ago

I have 2 view models: ProductsViewModel for products page and ProductViewModel for product detail page.

In ProductsViewModel, I already have a function permalinkCategory to create a URL to product category or featuredImage function to generate the product's thumbnail.

How can I reuse those function without rewrite functions in ProductViewModel? Should I combine 2 above view models in each controller and return to the view?

Thank you.

brendt commented 4 years ago

@phuclh there are several ways to do this:

The second options is my preference because it's more flexible and doesn't abuse inheritance. But that's up to you.

phuclh commented 4 years ago

@phuclh there are several ways to do this:

  • Have an abstract view model which contains the shared logic, and extend both view models from that one
  • Create one or several services dedicated to this shared functionality, and inject them into the viewmodel when constructing it

The second options is my preference because it's more flexible and doesn't abuse inheritance. But that's up to you.

Thank you for your solutions. If using the 2nd option. Where you prefer to put those service classes in the domain oriented design?

brendt commented 4 years ago

If they are specifically used for parsing data to views, definitely in the application layer. Possibly even within as a sub-namespace of the ViewModels namespace.