Статьи

Объектно-ориентированное программирование в WordPress: Документ Плагин II

На этом этапе серии мы готовы продвинуться вперед с завершением нашего плагина, документируя наши файлы, классы, функции, переменные и многое другое.

Хотя это последний шаг, который мы фактически должны завершить, это не последний пост в серии, так как мы продолжим рассмотрение нескольких сложных тем в объектно-ориентированном программировании.

Но прежде чем мы это сделаем, давайте доведем наш плагин до версии 1.0, применяя на практике все, что мы узнали в предыдущей статье .

Конечно, как и во всех предыдущих статьях, я рекомендую ознакомиться со всем, что мы уже рассмотрели, чтобы вы были полностью в курсе не только работы, которую мы проделали в предыдущей статье, но и того, как мы на самом деле добрались до последних моментов, которые мы обсуждаем в этой статье.

  1. Введение
  2. Классы
  3. Типы
  4. Управляющие структуры: условные высказывания
  5. Управляющие структуры: петли
  6. Функции и атрибуты
  7. Сфера
  8. Сборка плагина I
  9. Сборка плагина II
  10. Документ Плагин I

Рассмотрим и рассмотрим все это, давайте начнем с документирования каждого из наших файлов.

Существует множество способов документировать этот плагин:

  • Сначала мы могли документировать все заголовки файлов, затем мы могли возвращаться и документировать классы, затем мы могли возвращаться и документировать переменные, а затем мы могли документировать функции.
  • Мы могли бы документировать каждый файл за раз и кратко обсудить все, что включено для каждого файла.

Очевидно, что опция даст больше документации на раздел, но должна привести к гораздо менее утомительной статье и намного легче понять поток управления для всего плагина.

С этой целью мы будем работать с плагином, файл за файлом, представляя документацию для каждого фрагмента кода, который у нас есть, а затем мы обсудим любые интересные моменты после кода.

Наконец, мы убедимся, что мы ссылаемся на окончательную версию плагина в конце статьи. С этим сказал, давайте начнем.

Напомним, что основным файлом для запуска плагина является файл single-post-meta-manager.php, расположенный в корне каталога плагина.

Вот как выглядит полностью документированная версия файла. Внимательно читайте каждый комментарий, обращая внимание не только на его формат, но и на содержание, которое он предоставляет.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
/**
 * The file responsible for starting the Single Post Meta Manager plugin
 *
 * The Single Post Meta Manager is a plugin that displays the post meta data
 * associated with a given post.
 * including the necessary dependencies and starting the plugin.
 *
 * @package SPPM
 *
 * @wordpress-plugin
 * Plugin Name: Single Post Meta Manager
 * Plugin URI: http://github.com/tommcfarlin/post-meta-manager
 * Description: Single Post Meta Manager displays the post meta data associated with a given post.
 * Version: 1.0.0
 * Author: Tom McFarlin
 * Author URI: http://tommcfarlin.com
 * Text Domain: single-post-meta-manager-locale
 * License: GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 * Domain Path: /languages
 */
 
// If this file is called directly, then about execution.
if ( ! defined( ‘WPINC’ ) ) {
    die;
}
 
/**
 * Include the core class responsible for loading all necessary components of the plugin.
 */
require_once plugin_dir_path( __FILE__ ) .
 
/**
 * Instantiates the Single Post Meta Manager class and then
 * calls its run method officially starting up the plugin.
 */
function run_single_post_meta_manager() {
 
    $spmm = new Single_Post_Meta_Manager();
    $spmm->run();
 
}
 
// Call the above function to begin execution of the plugin.
run_single_post_meta_manager();

В приведенном выше коде обратите внимание, что мы определили заголовок файла в соответствии с соглашениями, которые мы изложили в предыдущей статье. Мы также сохранили необходимые теги заголовков плагинов, чтобы WordPress правильно их читал.

Обратите внимание, что в этом случае мы включили их в пользовательский тег @wordpress-plugin . Это не обязательно, но помогает отделить комментарии заголовка файла от обязательных комментариев плагина.

Наконец, обратите внимание, что мы увеличили версию этого плагина до 1.0 , и мы также дали этому плагину значение SPMM для SPMM которое меньше, чем Single Post Meta Manager . Мы будем использовать это на протяжении всего плагина.

Далее, давайте обратим наше внимание на все файлы, которые находятся в каталоге include.

Поскольку эти файлы требуются прежде всего в каталоге администратора, имеет смысл рассмотреть каждый из этих файлов по отдельности, а затем завершить наше обсуждение оставшимися файлами в каталоге администратора.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
<?php
 
/**
 * The Single Post Meta Manager is the core plugin responsible for including and
 * instantiating all of the code that composes the plugin
 *
 * @package SPMM
 */
 
/**
 * The Single Post Meta Manager is the core plugin responsible for including and
 * instantiating all of the code that composes the plugin.
 *
 * The Single Post Meta Manager includes an instance to the Single Post Manager
 * Loader which is responsible for coordinating the hooks that exist within the
 * plugin.
 *
 * It also maintains a reference to the plugin slug which can be used in
 * internationalization, and a reference to the current version of the plugin
 * so that we can easily update the version in a single place to provide
 * cache busting functionality when including scripts and styles.
 *
 * @since 1.0.0
 */
class Single_Post_Meta_Manager {
 
    /**
     * A reference to the loader class that coordinates the hooks and callbacks
     * throughout the plugin.
     *
     * @access protected
     * @var Single_Post_Meta_Manager_Loader $loader Manages hooks between the WordPress hooks and the callback functions.
     */
    protected $loader;
 
    /**
     * Represents the slug of hte plugin that can be used throughout the plugin
     * for internationalization and other purposes.
     *
     * @access protected
     * @var string $plugin_slug The single, hyphenated string used to identify this plugin.
     */
    protected $plugin_slug;
 
    /**
     * Maintains the current version of the plugin so that we can use it throughout
     * the plugin.
     *
     * @access protected
     * @var string $version The current version of the plugin.
     */
    protected $version;
 
    /**
     * Instantiates the plugin by setting up the core properties and loading
     * all necessary dependencies and defining the hooks.
     *
     * The constructor will define both the plugin slug and the verison
     * attributes, but will also use internal functions to import all the
     * plugin dependencies, and will leverage the Single_Post_Meta_Loader for
     * registering the hooks and the callback functions used throughout the
     * plugin.
     */
    public function __construct() {
 
        $this->plugin_slug = ‘single-post-meta-manager-slug’;
        $this->version = ‘1.0.0’;
 
        $this->load_dependencies();
        $this->define_admin_hooks();
 
    }
 
 
 
    /**
     * Imports the Single Post Meta administration classes, and the Single Post Meta Loader.
     *
     * The Single Post Meta Manager administration class defines all unique functionality for
     * introducing custom functionality into the WordPress dashboard.
     *
     * The Single Post Meta Manager Loader is the class that will coordinate the hooks and callbacks
     * from WordPress and the plugin.
     * $loader class property.
     *
     * @access private
     */
    private function load_dependencies() {
 
        require_once plugin_dir_path( dirname( __FILE__ ) ) .
 
        require_once plugin_dir_path( __FILE__ ) .
        $this->loader = new Single_Post_Meta_Manager_Loader();
 
    }
 
    /**
     * Defines the hooks and callback functions that are used for setting up the plugin stylesheets
     * and the plugin’s meta box.
     *
     * This function relies on the Single Post Meta Manager Admin class and the Single Post Meta Manager
     * Loader class property.
     *
     * @access private
     */
    private function define_admin_hooks() {
 
        $admin = new Single_Post_Meta_Manager_Admin( $this->get_version() );
        $this->loader->add_action( ‘admin_enqueue_scripts’, $admin, ‘enqueue_styles’ );
        $this->loader->add_action( ‘add_meta_boxes’, $admin, ‘add_meta_box’ );
 
    }
 
    /**
     * Sets this class into motion.
     *
     * Executes the plugin by calling the run method of the loader class which will
     * register all of the hooks and callback functions used throughout the plugin
     * with WordPress.
     */
    public function run() {
        $this->loader->run();
    }
 
    /**
     * Returns the current version of the plugin to the caller.
     *
     * @return string $this->version The current version of the plugin.
     */
    public function get_version() {
        return $this->version;
    }
 
}

Очевидно, что в этот конкретный файл было добавлено много новых комментариев; однако, это должно быть очень самоочевидно относительно того, что делают каждое свойство класса, конструктор и внутренние функции.

Главное, на что нужно обратить внимание — помимо того, как информация координируется через плагин, — это то, как мы придерживались стандартов, определенных в предыдущей статье.

Однако обратите внимание, что мы взяли на себя смелость, если не используем определенные теги и / или функции документации, когда они не имеют отношения к делу. Это то, что мы продолжим делать до конца статьи.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
 
/**
 * The Single Post Meta Manager Loader is a class that is responsible for
 * coordinating all actions and filters used throughout the plugin
 *
 * @package SPMM
 */
 
/**
 * The Single Post Meta Manager Loader is a class that is responsible for
 * coordinating all actions and filters used throughout the plugin.
 *
 * This class maintains two internal collections — one for actions, one for
 * hooks — each of which are coordinated through external classes that
 * register the various hooks through this class.
 *
 * @since 1.0.0
 */
class Single_Post_Meta_Manager_Loader {
 
    /**
     * A reference to the collection of actions used throughout the plugin.
     *
     * @access protected
     * @var array $actions The array of actions that are defined throughout the plugin.
     */
    protected $actions;
 
    /**
     * A reference to the collection of filters used throughout the plugin.
     *
     * @access protected
     * @var array $actions The array of filters that are defined throughout the plugin.
     */
    protected $filters;
 
    /**
     * Instantiates the plugin by setting up the data structures that will
     * be used to maintain the actions and the filters.
     */
    public function __construct() {
 
        $this->actions = array();
        $this->filters = array();
 
    }
 
    /**
     * Registers the actions with WordPress and the respective objects and
     * their methods.
     *
     * @param string $hook The name of the WordPress hook to which we’re registering a callback.
     * @param object $component The object that contains the method to be called when the hook is fired.
     * @param string $callback The function that resides on the specified component.
     */
    public function add_action( $hook, $component, $callback ) {
        $this->actions = $this->add( $this->actions, $hook, $component, $callback );
    }
 
    /**
     * Registers the filters with WordPress and the respective objects and
     * their methods.
     *
     * @param string $hook The name of the WordPress hook to which we’re registering a callback.
     * @param object $component The object that contains the method to be called when the hook is fired.
     * @param string $callback The function that resides on the specified component.
     */
    public function add_filter( $hook, $component, $callback ) {
        $this->filters = $this->add( $this->filters, $hook, $component, $callback );
    }
 
    /**
     * Registers the filters with WordPress and the respective objects and
     * their methods.
     *
     * @access private
     *
     * @param array $hooks The collection of existing hooks to add to the collection of hooks.
     * @param string $hook The name of the WordPress hook to which we’re registering a callback.
     * @param object $component The object that contains the method to be called when the hook is fired.
     * @param string $callback The function that resides on the specified component.
     *
     * @return array The collection of hooks that are registered with WordPress via this class.
     */
    private function add( $hooks, $hook, $component, $callback ) {
 
        $hooks[] = array(
            ‘hook’ => $hook,
            ‘component’ => $component,
            ‘callback’ => $callback
        );
 
        return $hooks;
 
    }
 
    /**
     * Registers all of the defined filters and actions with WordPress.
     */
    public function run() {
 
         foreach ( $this->filters as $hook ) {
             add_filter( $hook[‘hook’], array( $hook[‘component’], $hook[‘callback’] ) );
         }
 
         foreach ( $this->actions as $hook ) {
             add_action( $hook[‘hook’], array( $hook[‘component’], $hook[‘callback’] ) );
         }
 
    }
 
}

Обратите внимание, что этот класс является более или менее основным компонентом плагина, поскольку он координирует все действия и фильтры, используемые в плагине. Этот плагин централизует всю регистрацию и координацию хуков, которые используются во всем плагине.

Наконец, когда вызывается run , все ловушки регистрируются в WordPress, поэтому плагин запускает каждое из зарегистрированных действий и фильтров.

На данный момент мы готовы обратить наше внимание на файлы, расположенные в директории администратора плагина.

Хотя файл состоит из пары файлов PHP, он также состоит из файла CSS. Для этой статьи мы не собираемся документировать файлы CSS; однако Кодекс WordPress действительно определяет документацию для этого.

Сейчас же давайте продолжим документировать классы и файлы, которые существуют в каталоге admin .

Класс администратора Meta Manager с одним постом несет единственную ответственность: определяет функциональность для отображения мета-блока и его стилей для панели мониторинга.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
 
/**
 * The Single Post Meta Manager Admin defines all functionality for the dashboard
 * of the plugin
 *
 * @package SPMM
 */
 
/**
 * The Single Post Meta Manager Admin defines all functionality for the dashboard
 * of the plugin.
 *
 * This class defines the meta box used to display the post meta data and registers
 * the style sheet responsible for styling the content of the meta box.
 *
 * @since 1.0.0
 */
class Single_Post_Meta_Manager_Admin {
 
    /**
     * A reference to the version of the plugin that is passed to this class from the caller.
     *
     * @access private
     * @var string $version The current version of the plugin.
     */
    private $version;
 
    /**
     * Initializes this class and stores the current version of this plugin.
     *
     * @param string $version The current version of this plugin.
     */
    public function __construct( $version ) {
        $this->version = $version;
    }
 
    /**
     * Enqueues the style sheet responsible for styling the contents of this
     * meta box.
     */
    public function enqueue_styles() {
 
        wp_enqueue_style(
            ‘single-post-meta-manager-admin’,
            plugin_dir_url( __FILE__ ) .
            array(),
            $this->version,
            FALSE
        );
 
    }
 
    /**
     * Registers the meta box that will be used to display all of the post meta data
     * associated with the current post.
     */
    public function add_meta_box() {
 
        add_meta_box(
            ‘single-post-meta-manager-admin’,
            ‘Single Post Meta Manager’,
            array( $this, ‘render_meta_box’ ),
            ‘post’,
            ‘normal’,
            ‘core’
        );
 
    }
 
    /**
     * Requires the file that is used to display the user interface of the post meta box.
     */
    public function render_meta_box() {
        require_once plugin_dir_path( __FILE__ ) .
    }
 
}

Обратите внимание, что у класса выше очень мало функциональных деталей. Прежде всего, класс поддерживает ссылку на версию плагина, таблицу стилей, используемую для стилизации мета-блока, и функцию, необходимую для фактической визуализации мета-блока.

Напомним, что все это настроено в файле основного плагина и загрузчике. Это помогает отделить логику, которая существует в плагине, чтобы каждый класс мог сосредоточиться на том, что его основная цель.

Конечно, последняя часть плагина опирается на фактический частичный файл, который содержит разметку, необходимую для отображения мета-блока.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
/**
 * Displays the user interface for the Single Post Meta Manager meta box.
 *
 * This is a partial template that is included by the Single Post Meta Manager
 * Admin class that is used to display all of the information that is related
 * to the post meta data for the given post.
 *
 * @package SPMM
 */
?>
<div id=»single-post-meta-manager»>
 
    <?php $post_meta = get_post_meta( get_the_ID() );
    <table id=»single-post-meta-manager-data»>
    <?php foreach ( $post_meta as $post_meta_key => $post_meta_value ) { ?>
        <tr>
            <td class=»key»><?php echo $post_meta_key;
            <td class=»value»><?php print_r( $post_meta_value[0] );
        </tr>
    <?php } ?>
    </table>
 
</div><!— #single-post-meta-manager —>

Это должно быть относительно очевидным; однако, чтобы завершить, обратите внимание, что этот файл принимает текущий идентификатор сообщения (с помощью функции get_the_ID() ), читает метаданные сообщения и затем просматривает его, создавая таблицу, в которой отображаются ключи и значения.

На данный момент мы завершили реализацию нашего плагина. От внедрения практики программирования объектно-ориентированного программирования до документирования кода.

Вы можете получить финальную версию плагина на GitHub ; однако мы продолжим наше объектно-ориентированное обсуждение еще на нескольких постах, чтобы мы могли изучить несколько более сложных тем, таких как наследование, абстракция и другие темы.

В то же время, если у вас есть вопросы или комментарии о плагине, не стесняйтесь оставлять их в комментариях!