- WordPress 3 Plugin Development Essentials
- Brian Bondari Everett Griffiths
- 1378字
- 2021-04-09 21:19:56
Basic organization
The simple recommendation here is to keep your code consistently organized. If someone is looking through your code months from now, will he be able to follow the method to your madness? If you are consistent, people will be able to follow your logic more easily, even if they don't agree with it. Consistency should prevail throughout your variable names, function names, documentation, file names, and folder structure: keep it sensible and clean.
One other tip that we have learned through many hours of frustration seems profoundly simple: a "unit" of code should fit on one screen without scrolling. In general, if you can't see it, you can't get it uploaded into your brain for full comprehension. What is a "unit"? Usually it is a function, but sometimes it can be a logical block or a group of related tasks. Functions are easier to test, so they make for better units. The bottom line is to take small bites and if your "units" fit snugly on the screen instead of scrolling across several pages, then your code will be much easier to understand and debug.
Here are the main points to consider when organizing your code:
- Isolate tasks into functions
- Use classes
- Use descriptive variable names
- Use descriptive function names
- Separate logic and display layers
- Go modular, to a point
- Avoid short tags
Isolate tasks into functions
A function, as its name suggests, performs a certain task, but structuring them can be a bit of an art. Any time you find yourself copying and pasting identical code (or even similar code), that should be a glaring red flag that it's time to consolidate it into one place by putting it into a function. Just like having a single stylesheet for your website gives the designer a single place to make global changes, a function should give the developer one place to alter a particular behavior.
A good rule of thumb when writing functions is that they should not accept more than three inputs. Otherwise, they become difficult to use. You can package multiple inputs into a single associative array (a.k.a. a "hash"), or you could restructure your code into multiple functions. Again, find a clean solution.
Use classes
For new developers, the whole notion of objects and classes may seem something of a black art. It may feel needlessly complex, and to be fair, in some scenarios it is. However, the more you develop, the more you will gravitate toward object-oriented code because it allows for better organization, maintainability, and classes are much easier to extend.
Anyone familiar with CSS can appreciate the beauty of overriding a behavior. In the same way that you can override a style declaration from a *.css
file with a local declaration, you can override a PHP class function by extending the class and redefining the function. We will see some examples of this later in this book.
Use descriptive variable names
PHP does not impose many restrictions on variable names, and there are differing naming strategies that you may employ. Compare this to Java, where using the incorrect case or underscores in your variable names is tantamount to heresy. Common naming strategies include $lower_case_with_underlines and $camelCase, and since PHP does not use distinct glyphs to distinguish arrays from scalar variables (like Perl, which distinguishes a $scalar from a @array), it can be useful to include the data type in the variable name, for example, $records_array.
Whichever method you use, make sure that the names adequately describe the contents of the variable in the context in which they appear. Avoid single letters and avoid long-winded, overly complicated names. In general, find the shortest name that accurately represents the variable's purpose. It may seem esoteric, but in order to understand your code, it must enter your brain through the construct of the English language (or in whatever language you tend to think). If your variable names are unclear, your brain will have to work harder to understand what your code is doing, so take the time to be descriptive and clear.
Use descriptive function names
As with your variable names, your function names should accurately describe what the functions do. It is common in most languages to have functions that get or set attributes, such as getHeader()
or setPageWidth()
.
There are a few caveats to mention with PHP function names: first of all they are not case sensitive. For example, add_action()
, aDD_aCtIoN()
, or ADD_ACTION()
are all interpreted identically. For the sake of clarity and ease of searching, always call your functions using the same case as their definitions.
Function names starting with a single underscore (for example, _my_private_function()
) have historically been used to denote private functions—that is functions intended for use by other functions and not for direct use by the "outside world". With PHP 5, you can control the access to a class's functions as public, private, or protected, but the underscore is still often used as a helpful reminder.
"Magical" functions in PHP use names starting with two underscores (for example, __construct()
). They are used to perform special tasks inside of a PHP class. Although you can name your functions in this way provided there are no name collisions, it is not recommended because they may be mistaken for magic PHP functions. For example, WordPress uses the __() function for localization, but we do not recommend using function names that begin with two underscores or whose names are very non-descriptive.
Lastly, your code will be much easier to navigate if you alphabetize your functions by name. Some text editors, particularly IDEs, will provide a menu to jump to each function. Alphabetizing works especially well if you put the magic functions (with two leading underscores) before the private functions (with a single leading underscore) before the public functions (with no leading underscores). The quicker you can navigate your code, the quicker you will be able to debug and change it.
Separate logic and display layers
It doesn't matter whether you are using procedural or object-oriented code, you should still separate your logic from your presentation. In laymen's terms, that means that you should keep if-statements, loops, or any other logical flows out of your HTML as much as possible.
Endlessly concatenating bits of HTML with variables and having to debug your display layers is a huge waste of time that is accepted as common practice by a staggering number of developers. You will be way ahead of the curve if you keep your HTML display logic as simple and static as possible, and keep your complicated calculations in separate functions and files. We will show you several examples of how to avoid messy concatenations using PHP functions like sprintf()
as well as a few of our own parsing functions.
Go modular, to a point
Normally, there are strong admonitions to reuse your code whenever possible, but it is necessary to mention the caveats required for making your code portable and modular. When it comes to plugin development, sometimes you can get into trouble if your code pokes its head too far out of its own folder and starts referencing JavaScript libraries, CSS files, or even scripts that it assumes will be present in any WordPress install.
The only tie to the parent application should be through the API. It may go against your instincts to copy a second version of an image or a JavaScript library into your plugin's directory, but it will ensure that your plugin is self-sustaining and not susceptible to changes outside of its own folder.
Avoid short tags
Simply because you can configure PHP to use "<?" and "?>" (a.k.a. "short tags") to demarcate PHP code, that doesn't mean you should. Short tags are fool's gold! Even if your web server supports them, don't expect everyone in the neighborhood to join your club. Apart from making distribution of your plugin risky, short tags can cause XML files to get interpreted as PHP because they too begin with "<?".
We have personally discovered many plugins in the WordPress repository that made the sophomoric mistake of using short tags, forcing us to have to debug them immediately after installing them. It sounds harsh, but using short tags is a sure-fire way to doom your plugin to the rubbish pile.
- 中文版CorelDRAW 2022基礎教程
- 中文版After Effects 2021入門教程
- UG NX 9.0中文版 基礎教程 (UG工程師成才之路)
- 中文版 Photoshop CC 從入門到精通
- SOLIDWORKS Visualize 實例詳解(微視頻版)
- Android User Interface Development: Beginner's Guide
- SolidWorks 2018有限元:運動仿真與流場分析自學手冊
- AutoCAD 2016入門與提高(超值版)
- 零基礎學會聲會影2018(全視頻教學版)
- UG NX 12.0中文版從入門到精通
- Photoshop+CorelDRAW 字體設計與創意:草圖/實現/包裝(微課版)
- Photoshop CC2017圖像處理實例教程
- Flash CS5動畫設計教程
- UG NX 10中文版完全自學手冊
- Instant MDX Queries for SQL Server 2012