A
A
Arman2017-03-13 18:05:48
Yii
Arman, 2017-03-13 18:05:48

What are the disadvantages of writing all the field rules in the Yii2 AR model?

What tasks do I solve:
1. Checking the validity of the data before saving it to the database, it doesn’t matter if you received it from the user or a crooked programmer has assembled a model - you need to check the data before saving. We only check the fields that go to the database, for everything else we use a form model that must assemble the main AR model so that it can be saved.
2. Do not copy-paste logic for different form models. There is an AR model User, he has a password, now password rules: registration form, login form, password change form after recovery, password change in the account, password change in the admin panel (your password), password change in the admin panel of another user, etc. d. a bunch of forms where there is a copy-paste of the rules. And now what to do if you set the task to increase the minimum. number of characters in the password or put another check on the complexity of the password?
As I see the solution:
1. The database does not contain any logic, a stupid black box, but the model in front of it decides everything (the last resort, there is nowhere to retreat behind ... the database)
2. The AR model is the heaviest
2.1 contains all the rules for all (! ) database fields. Protection from fools and crooked hands is not saved until everything is done wisely.
2.2 scripting method rewritten so that all fields are unsafe for load(). The controller tells the model what fields it can work with, or the form model (the successor of the AR model) tells what fields it can work with. and only then load() works
2.3 when save() runs validators only for fields that have been updated
So, having written a model once, you can scatter tasks with this model to other developers who will write different forms, different APIs, and I will be more or less sure that there will be whole, valid data in the database. Not to mention that tomorrow it will not be necessary to search for the places where the data is checked for this model (the task was to make some field optional or make a float instead of an int).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexKuznec, 2017-03-23
@Arik

Kind of like ActiveRecord does it all: validation of incoming values, scripts to control when which attributes can be changed.
save() also seems to save only changed values ​​(you can dig into the source or documentation, since I did not dig deep in this place).
As an example, you can see the implementation of registration and logins (several forms and controllers) in the advanced application.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question