Laravel Beyond Crud Course Flashcards
Calculated fields (total_price)
Calculated fields can be moved into database as stored field, being calculated only on create or updates. Calculation logic can be moved to observers or event subscribers.
Extend Eloquent Collections
You can define your own collections class to model, and add all custom filters there.
Extend Query Builder
You can define your own query builder class to model, and add all scopes there. As a bonus you’ll get autocompletion.
Testing DTO
We don’t test DTO’s. At most we can test mapping between dto and user input.
Testing actions composed from other actions
We should test all internally used actions separatly, and write kind of integration test for that complex action.
Testing Collections and Query Builders.
We should write tests on these. This test should be small and just check if seeded by factories data is filtered correctly.
Testing Event Subscribers
We can send event directly to subscribe.
And since object are passed by reference we can check original objects in assertions.
Testing Factories
Self-written factories could be used to gain auto completion and customizing data/relations. T
hey can also use Immutable methods. Which returns clone of original objects with some changed parameter. So you can use this clone, but original object stays unchanged.
In laravel 8 default factories should be improved, so it may not be need in self-written solutions.
The State Pattern
Model states, such as paid, canceled or overdue invoices. This can be moved to separate classes, by creating base “InvoiceState” abstract class with needed method signatures (getColour, shouldBePaid etc) And then creating corresponding “State” classes (Paid, Canceled, Overdue) which will extend it and just return correct values from that methods.
And then on the model level need to be done only mapping between database “status field” and corresponding class.
Third-party integrations
If you need to communicate with some third-party – you can create a Gateway. Which will map your API call input from DTO. Then perform a request, and finally map API output to your DTO. In that case all specific logic to map data between your application and third-party service will be grouped in that Gateway.
This logic, including mapping DTO’s should be moved to separate layer (not application or domain). For example Support.
View Models
View models hold all information which is used in the views, or json responses. You can use same view model for create and update. Also you can use same view model in a same way for views and ajax requests. Spatie has package to make this easier.