Answer the question
In order to leave comments, you need to log in
PHP using traits to split a class into parts
Hello!
The class contains many methods for working with users. Is it normal if the functionality of a class is divided by traits. For example, to work with personal messages, a profile, etc. Is this practiced?
Thank you.
Answer the question
In order to leave comments, you need to log in
No, it's not normal. It is normal to bring some bootstrap code into traits, or a proxy code for the implementation of method composition, but it is the implementation of classes that is not ok.
Here is an example, you have a bold class to manage posts, profile, etc. Separate it into separate classes, one for handling messages only, the other for profile only. Inject them into the general class manager, and prescribe all the interfaces (that is, you also need to write interfaces to the classes, in the IDE you can simply select the class interface and save it separately). In this case, it's okay to trait methods, as they just proxy calls to their class instance.
You tie the rest of the code only to the interfaces of those parts that they need. Let's say some class does not need a profile manager, it only needs a message manager. In this case, you can only inject it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question