In most of the frameworks you have model classes that represents row in the database.
For example php code:
class User extends Model {}
I'm giving Laravel eloquent example but this is true for most php frameworks.
Then you add the relationships in the class:
public function pictures()
{
return $this->hasMany('App\Picture');
}
Then you add some methods like this:
public function deleteComments()
{
// delete comments code here
}
My first question is: Is this good design architecture because after years when the project becomes large you will have many relationships (pictures, comments, posts, subscriptions, etc connected to the user). The class could become 10k lines of code or so.
In that case, the class will become very large and hard to maintain. Also the Single Responsible Principle maybe is violated because you have too many methods in one class.
Also if I want to use the class it in another app I cannot, simply because I'll have to pull also the pictures, comments and etc in the second application(website).
If I make other classes like "UserPictures
", "UserPictureDeleter
" the code will get more complicated.
So is this good practice and if not do you have any suggestions on how to make the code not bloated with so many methods but easy to use.
Do you agree that all these methods belong to the User
class?
Laravel and some another framework provide Active Record conception in their base classes of model. The main idea of Active Record is a representation of table row as an object that includes data of a row and methods of work with databases.
Using of Active Record pattern is fully justified in small simple applications because this pattern gives an ability to fast develop your application. But if your application has a lot of code and difficult business logic, Active Record will make many problems in the architecture of your application. Active Record can make the following problems:
The solution to those problems is using of OOP abstractions instead of using of table rows abstractions. For example, you can use Domain Model and Domain-driven design. This approach is better than Active Record pattern for large applications.
Unfortunately, those concepts are too large-volume for explanation in this post, but you can read "Domain Driven Design" by Eric Evans. It is a good book about application design. Also, you can find many articles about those concepts in google. For example Building a Domain Model, Implementing Domain-Driven Design in PHP (Laravel)
You could improve your model with Interfaces. If you need one class to inherit a certain behavior common to another, having designed the interface, you need the new class to only implement the interface.
Interfase based programming
coding to interfase in PHP
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With