WordPress: code structure

EDIT: I’ve posted them separately here wordpress.stackexchange.com/questions/137672/… and here wordpress.stackexchange.com/questions/137673/…. I’ll vote to delete this one.

I’m working on a WordPress site, and I’m having a few questions about structuring my PHP code.
Although I’ve have experience with structuring code in other frameworks, I’m wondering how you would do this in WordPress. I might have known some of this if I was more fluent in PHP.

More specifically:

  • Separation of view and logic

I find that very easily my views become cluttered with logic, e.g. null checks, email validation, and retrieving values from the post object. How would you separate this out in WordPress? Is there any sort of MVC framework?

  • Common functionality between my own plugins

I read that when creating new post types, creating a settings page, and creating a new taxonomy, you should create a plugin. So I have done that. But I have functionality, which could be generalized, or are identical, in my plugins. An example of this would be the function which saves to the database. Since everything seems to be put in the global scope, if there is such a thing in PHP, should I create another plugin with shared functionality, or put shared functionality in the functions.php file?

  • Is everything global?

As I mention above, is everything global in WordPress? My impression is that other plugins might very well have function names that clash with my function names; that’s why you prefix functions with your themes theme name. Is there a way to avoid this?

Thank you for your time, and sorry if this is duplicate questions.

Answer

I find that very easily my views become cluttered with logic, e.g. null checks, email validation, and retrieving values from the post object. How would you separate this out in WordPress? Is there any sort of MVC framework?

There is no clear separation enforced by WordPress and there is extremely wide range of styles and opinions on this. Simply put you are either on your own managing this in your code or you can look for third party framework and/or convention to make use of.

should I create another plugin with shared functionality, or put shared functionality in the functions.php file?

Since everything is in global scope the question “where things go” is primarily semantic rather than technical. Again you either look for opinion or make up your own about it.

As I mention above, is everything global in WordPress? My impression is that other plugins might very well have function names that clash with my function names; that’s why you prefix functions with your themes theme name. Is there a way to avoid this?

Use PHP namespaces. Well, as above even this is more of an opinion since natively WP aims for compatibility with obsolete PHP 5.2 version and isn’t making use of namespaces in core.

Attribution
Source : Link , Question Author : ptf , Answer Author : Rarst

Leave a Comment