Skip to content

Class aliases and template functions

Fulvio Notarstefano edited this page Oct 21, 2019 · 4 revisions

Plugins that implement the framework may find the necessity to use common helpers found in the SV_WC_Helper or SV_WC_Plugin_Compatibility classes (or others) in contexts where using fully namespaced classes is not advisable. This is often the case of template files. If an admin or theme developer overrides a template they'd probably copy over a reference to namespace/version of the framework which is deemed to be updated. As such, the template will generate a PHP error once the referenced framework class is gone.

There are two complimentary ways to get around this issue.

Define helpers or functions in the plugin that call specific framework methods

Some plugins create a set of template functions or static helper classes for common operations in the plugin's context. These functions or methods, in turn, could reference the framework helpers. Procedural functions would be the "WordPress way" as they're the most common accepted approach to share code in namespace-free contexts and they're easier to use for most of the WordPress users. If they live in the global namespace, they won't need to care about namespace structure changes, even within the plugin, not just the framework.

Define class aliases for framework methods

Additionally, templates and namespace-free contexts could also make use of common helpers defined in Framework SV_WC_Helper or SV_WC_Plugin_Compatibility classes without referencing their namespace/framework version. A way to do so is to define class aliases (PHP 5.3+). For example:

class_alias( SV_WC_Helper::class, '\\SkyVerge\\WooCommerce\\<Plugin_Name>\\Helper' );
class_alias( SV_WC_Plugin_Compatibility::class, '\\SkyVerge\\WooCommerce\\<Plugin_Name>\\Compatibility' );

(Note this example does not include the full namespaced reference to the FW classes, which you need to account for).

This code would create two non-namespaced classes WC_My_Plugin_Helper and WC_My_Plugin_Compatibility which would be identical in content to the class defined as the first argument of the function. Most modern IDEs are also able to parse this information and reference correctly each class, for static analysis, error detection, or code jump.

The ideal placement for class aliases of this kind could be the plugin main class constructor or the child instance of SV_WC_Plugin::__construct() as the helpers have been already loaded at that point. If a class alias is needed for other framework classes that are not immediately available in the constructor context, then they should be placed in a safer location.