Why using Trait to transform a big Class in multiple parts

During the upgrade (and upgrade to the WP Code Standards) of a php source code sometimes of more than 10 years old, the file problem of a class of nearly 10,000 lines arose. Indeed, the phpcs process is very slow and it can be difficult to group the added functions over the years. Subclassing or specific class with new names is not easy and requires a lot of changes in the files. Searching through the docs and forums, few people cite the approach with “Trait” that look like a very simple php class.

Take the case of a method set that manages a page of admin settings and related functions in the meta boxes.

We create a file, the Trait is inside, we copy these said functions. No renaming, the pseudo variable $ this remains operative …

  • The call to the Trait is at the beginning of the class that is reorganized with “use”.

So it remains to set up the file containing the Trait (preferably only one per file)

It is required before the class containing the “use” otherwise a fatal error is caused.

And now, part by part, it is easier to change the code obviously on the admin side.