Answer the question
In order to leave comments, you need to log in
How to isolate active record in laravel5?
I wondered how to safely isolate AR models and drive them around the application, through services, return them from repositories, etc. ?
Recently, I realized how not much messed up with the architecture of the application. The fact is that I sprayed AR models throughout the project, despite the fact that I used the repositories (as it turned out to be wrong).
For example, we have a simple code: $types = Type::with('fields')->get();
We take some types from the store. Suppose now it is AR, and tomorrow it is REST API or Query Builder, in general, the result will be different. Ie in the first case AR, on the second an array, in the third a collection. Not good.
I would like to bring this whole thing to one format and:
- do not be afraid that someone will intentionally or accidentally make $type->save() anywhere in the project
- return a single data type from the repository
- get away from AR logic, and transfer just data to views and between services (like through DTO)
Collections come to the rescue:
$type = Type::findOrFail($id);
collect($type);
$types = Type::with('fields')->get();
collect($types->toArray());
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => Array
(
[id] => 1
[alias] => test1
[name] => Новости
[description] =>
[fields] => Array
(
[0] => Array
(
[id] => 1
[type_id] => 1
[type] => test
[is_required] => 1
[validation] => 1
)
)
)
[1] => Array
(
[id] => 2
[alias] => test2
[name] => Статьи
[description] =>
[fields] => Array
(
[0] => Array
(
[id] => 2
[type_id] => 2
[type] => test
[is_required] => 1
[validation] => 2
)
)
)
[2] => Array
(
[id] => 3
[alias] => test3
[name] => Вакансии
[description] =>
[fields] => Array
(
)
)
)
)
Answer the question
In order to leave comments, you need to log in
We take certain types from storage. Suppose now it is AR, and tomorrow it is REST API or Query Builder, in general, the result will be different. Ie in the first case AR, on the second an array, in the third a collection. Not good.Create a service layer, write incoming and returning types (you can create new non-persistent model types) in methods. And the implementation inside the service can change, it will not affect anyone.
not afraid that someone will intentionally or accidentally do $type->save() anywhere in the projectWhy? AR is so used.
Is it right to get confused with AR insulationThis (anti)pattern was created and popular during rapid development, initially breaking SOLID. They usually do not bother with him, but rivet small projects.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question