Sử dụng namespace & Autoload trong Plugin Phần 1 đây cũng là cách viết add_meta_box trong class (ok)

https://code.tutsplus.com/vi/tutorials/using-namespaces-and-autoloading-in-wordpress-plugins-part-1--cms-27157

Ví dụ 1.

C:\xampp\htdocs\test\wp-content\plugins\lionel\lionel.php

<?php
/**
 * The plugin bootstrap file
 *
 * This file is read by WordPress to generate the plugin information in the
 * plugin admin area. This file also includes all of the dependencies used by
 * the plugin, registers the activation and deactivation functions, and defines
 * a function that starts the plugin.
 *
 * @link              http://.tutsplus.com/tutorials/using-namespaces-and-autoloading-in-wordpress-plugins-part-1
 * @since             0.1.0
 * @package           tutsplus_namespace_demo
 *
 * @wordpress-plugin
 * Plugin Name:       Tuts+ Namespace Demo
 * Plugin URI:        http://.tutsplus.com/tutorials/using-namespaces-and-autoloading-in-wordpress-plugins-part-1
 * Description:       Learn how to use Namespaces and Autoloading in WordPress.
 * Version:           0.1.0
 * Author:            Tom McFarlin
 * Author URI:        https://tommcfarlin.com/
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 */ 
// If this file is accessed directory, then abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}
// Include the files for rendering the display.
include_once( 'admin/class-meta-box.php' );
include_once( 'admin/class-meta-box-display.php' );
add_action( 'plugins_loaded', 'tutsplus_namespace_demo' );
/**
 * Starts the plugin by initializing the meta box, its display, and then
 * sets the plugin in motion.
 */
function tutsplus_namespace_demo() {
  $meta_box = new Meta_Box( new Meta_Box_Display() );
  $meta_box->init();
}

C:\xampp\htdocs\test\wp-content\plugins\lionel\admin\class-meta-box.php

<?php
/**
 * Represents a meta box to be displayed within the 'Add New Post' page.
 */
/**
 * Represents a meta box to be displayed within the 'Add New Post' page.
 *
 * The class maintains a reference to a display object responsible for
 * displaying whatever content is rendered within the display.
 */
class Meta_Box {
  /**
   * A reference to the Meta Box Display.
   *
   * @access private
   * @var    Meta_Box_Display
   */
  private $display;
  /**
   * Initializes this class by setting its display property equal to that of
   * the incoming object.
   *
   * @param Meta_Box_Display $display Displays the contents of this meta box.
   */
  public function __construct($display) {
    $this->display = $display;
  }
  /**
   * Registers this meta box with WordPress.
   *
   * Defines a meta box that will render inspirational questions at the top
   * of the sidebar of the 'Add New Post' page in order to help prompt
   * bloggers with something to write about when they begin drafting a post.
   */
  public function init() {
    add_action( 'add_meta_boxes', array( $this, 'wpdocs_register_meta_boxes' ) );
  }
  public function wpdocs_register_meta_boxes() {
    add_meta_box('tutsplus-post-questions','Inspiration Questions',array($this->display, 'render'),'post','side','high');
  }
}

C:\xampp\htdocs\test\wp-content\plugins\lionel\admin\class-meta-box-display.php

<?php
/**
 * Represents a meta box to be displayed within the 'Add New Post' page.
 */
/**
 * Represents a meta box to be displayed within the 'Add New Post' page.
 *
 * The class maintains a reference to a display object responsible for
 * displaying whatever content is rendered within the display.
 */
class Meta_Box {
  /**
   * A reference to the Meta Box Display.
   *
   * @access private
   * @var    Meta_Box_Display
   */
  private $display;
  /**
   * Initializes this class by setting its display property equal to that of
   * the incoming object.
   *
   * @param Meta_Box_Display $display Displays the contents of this meta box.
   */
  public function __construct($display) {
    $this->display = $display;
  }
  /**
   * Registers this meta box with WordPress.
   *
   * Defines a meta box that will render inspirational questions at the top
   * of the sidebar of the 'Add New Post' page in order to help prompt
   * bloggers with something to write about when they begin drafting a post.
   */
  public function init() {
    add_action( 'add_meta_boxes', array( $this, 'wpdocs_register_meta_boxes' ) );
  }
  public function wpdocs_register_meta_boxes() {
    add_meta_box('tutsplus-post-questions','Inspiration Questions',array($this->display, 'render'),'post','side','high');
  }
}

C:\xampp\htdocs\test\wp-content\plugins\lionel\admin\class-meta-box-display.php

<?php
/**
 * Defines the functionality required to render the content within the Meta Box
 * to which this display belongs.
 */
/**
 * Defines the functionality required to render the content within the Meta Box
 * to which this display belongs.
 *
 * When the render method is called, the contents of the string it includes
 * or the file it includes to render within the meta box.
 */
class Meta_Box_Display {
  /**
   * Renders a single string in the context of the meta box to which this
   * Display belongs.
   */
  public function render() {
      echo 'This is the meta box.';
  }
}

Ví dụ 2:

C:\xampp\htdocs\test\wp-content\plugins\lionel\lionel.php

<?php
/**
 * The plugin bootstrap file
 *
 * This file is read by WordPress to generate the plugin information in the
 * plugin admin area. This file also includes all of the dependencies used by
 * the plugin, registers the activation and deactivation functions, and defines
 * a function that starts the plugin.
 *
 * @link              http://.tutsplus.com/tutorials/using-namespaces-and-autoloading-in-wordpress-plugins-part-1
 * @since             0.1.0
 * @package           tutsplus_namespace_demo
 *
 * @wordpress-plugin
 * Plugin Name:       Tuts+ Namespace Demo
 * Plugin URI:        http://.tutsplus.com/tutorials/using-namespaces-and-autoloading-in-wordpress-plugins-part-1
 * Description:       Learn how to use Namespaces and Autoloading in WordPress.
 * Version:           0.1.0
 * Author:            Tom McFarlin
 * Author URI:        https://tommcfarlin.com/
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 */
// If this file is accessed directory, then abort.
if (!defined('WPINC')) {
  die;
}
// Include the files for rendering the display.
include_once 'admin/class-meta-box.php';
include_once 'admin/class-meta-box-display.php';
include_once 'admin/util/class-question-reader.php';
add_action('plugins_loaded', 'tutsplus_namespace_demo');
/**
 * Starts the plugin by initializing the meta box, its display, and then
 * sets the plugin in motion.
 */
function tutsplus_namespace_demo() {
  $meta_box = new Meta_Box(new Meta_Box_Display(new Question_Reader()));
  $meta_box->init();
}

C:\xampp\htdocs\test\wp-content\plugins\lionel\admin\class-meta-box.php

<?php
/**
 * Represents a meta box to be displayed within the 'Add New Post' page.
 */
/**
 * Represents a meta box to be displayed within the 'Add New Post' page.
 *
 * The class maintains a reference to a display object responsible for
 * displaying whatever content is rendered within the display.
 */
class Meta_Box {
  /**
   * A reference to the Meta Box Display.
   *
   * @access private
   * @var    Meta_Box_Display
   */
  private $display;
  /**
   * Initializes this class by setting its display property equal to that of
   * the incoming object.
   *
   * @param Meta_Box_Display $display Displays the contents of this meta box.
   */
  public function __construct($display) {
    $this->display = $display;
  }
  /**
   * Registers this meta box with WordPress.
   *
   * Defines a meta box that will render inspirational questions at the top
   * of the sidebar of the 'Add New Post' page in order to help prompt
   * bloggers with something to write about when they begin drafting a post.
   */
  public function init() {
    add_action( 'add_meta_boxes', array( $this, 'wpdocs_register_meta_boxes' ) );
  }
  public function wpdocs_register_meta_boxes() {
    add_meta_box('tutsplus-post-questions','Inspiration Questions',array($this->display, 'render'),'post','side','high');
  }
}

C:\xampp\htdocs\test\wp-content\plugins\lionel\admin\class-meta-box-display.php

<?php
/**
 * Defines the functionality required to render the content within the Meta Box
 * to which this display belongs.
 */
/**
 * Defines the functionality required to render the content within the Meta Box
 * to which this display belongs.
 *
 * When the render method is called, the contents of the string it includes
 * or the file it includes to render within the meta box.
 */
class Meta_Box_Display {
  /**
   * A reference to the object responsible for retrieving a question to display.
   *
   * @access private
   * @var    Question_Reader $question_reader
   */
  private $question_reader;
  /**
   * Initializes the class by setting the question reader property.
   *
   * @param Question_Reader $question_reader The object for retrieving a question.
   */
  public function __construct($question_reader) {
    $this->question_reader = $question_reader;
  }
  /**
   * Renders a single string in the context of the meta box to which this
   * Display belongs.
   */
  public function render() {
    $file     = dirname(__FILE__) . '\data\questions.txt';
    $question = $this->question_reader->get_question_from_file($file);
    echo wp_kses($question,array());
  }
}

C:\xampp\htdocs\test\wp-content\plugins\lionel\admin\data\questions.txt

1. Do you like who you are?
2. What would people say about you at your funeral?
3. What would you regret not doing in your life?
4. What’s the wisest thing you have ever heard someone say?
5. What lessons in life did you learn to hard way?
6. How often do your biggest worries and fears come true?
7. If you had one year left to live, what would you try to achieve?
8. Do you serve money or does money serve you?
9. Are you afraid of being your true self around others? Why?
10. What are you grateful for?
11. Have you done anything you are proud of lately?
12. Have you made any recent acts of kindness?
13. If you knew that you would die tomorrow, what questions would you ask yourself?
14. If your biggest fears came true, would it matter in five years from now?
15. How would you describe yourself?
16. Do you take people’s advice?
17. Do you get quickly offended?
18. Do you consider yourself to be a likable person?
19. ‘We make a living by what we get, we make a life by what we give’ – What does this mean to you?
20. Are you enriching the lives of others?
21. Are you living a meaningful life?
22. What makes a meaningful life?
23. Would you ever give up your life to save another?
24. How much would you be willing to sacrifice for people in poverty?
25. If you could live one day over and over again, what would you choose to do?
26. Do you think you are important and worthy of affection and love?
27. What would make you feel more worthy? What do you believe needs to be different about you?
28. What brings you down the most often?
29. Would you rather work less (and do the things you enjoy) and have less money?
30. Where do you find peace?
31. What is the most important quality you look for in another person?
32. What is your biggest dream in life?
33. What is your biggest fear?
34. How would the world be different if you had never been born?
35. What life lessons do you wish you knew 10 years ago?
36. If you could tell your younger self one thing, what would it be?
37. If your life was a movie, what would the title be?
38. If your life was a movie, would you enjoy watching it?
39. What does success mean to you?
40. If you could be a different person, who would you be?
41. What was the best day of your life? Why?
42. What do you look forward to most in life?
43. What bad habits do you want to ditch?
44. Who do you look up to and why?
45. Do you know your partners love language?
46. Do the people you love most know how much you love them?
47. Are you satisfied with the depth of your relationships?
48. What do you owe yourself?
49. Based on your current day-to-day life, what do you expect to achieve in 5 years from now?
50. Do you say ‘yes’ too often when you really want to say ‘no’? Why?
51. What did you learn yesterday?
52. What do you like about yourself?
53. Would you consider yourself to be a generous person?
54. Do you really listen when people talk to you?
55. What is the number one change you need to make in your life this year?
56. How many hours per week do you spend on the internet?
57. What are your most common negative thoughts? Are they logical?
58. Do you think it’s too late to do certain things in your life? Why?
59. If you could be the most influential person in the world, what would you change?
60. How much time do you spend with your family and friends?
61. Where do you want to be in 5 years from now?
62. Is your life complicated by unnecessary things?
63. How can you simplify your life and focus on the most important things to you?
64. What stresses you out?
65. What makes life easier?
66. How often do you give without expecting anything in return?
67. What is your greatest challenge?
68. What is most important to you in life? Are you giving it the time it deserves?
69. If you could send a message to the world, what would you say in 30 seconds?
70. What do you most regret never telling someone?
71. When was the last time you tried something new?
72. Are you afraid to speak your own opinion?
73. Do you give into others too often and feel resentful because of it?
74. Are you holding onto something that you need to put behind you?
75. How often do you let your fears hold you back?
76. Do the people in your life bring the best out of you?
77. How often do you make excuses?
78. What is one mistake that you will never do again?
79. Which is worse, failing or never giving it a shot?
80. What has grown you the most as a person – your challenges and trials or the comfortable yet enjoyable moments in life?
81. If you could choose to have no more challenges or obstacles in life, would you?
82. In one word, what is standing between you and your biggest goal?
83. How often do you go to bed feeling angry?
84. Would it be wrong to steal in order to feed a starving child?
85. If you paid more attention to the sad things in this world, would you feel more conflicted about it?
86. If we learn from our failures, then why is it so bad to fail?
87. What could you pay more attention to in life?
88. Why do we think of others the most when they’re no longer around?
89. What does it look like to make the most of your life?
90. What have you given up on?
91. How many people do you truly love and what are you doing for them?
92. Do you ask enough questions, or are you happy to settle for what you already know?
93. What were you doing when you last lost track of time?
94. Do you think you would be happy if you never had to work again?
95. How old would you be if you didn’t know how old you are?
96. If you could ask for one wish, what would it be?
97. What inspires you in life?
98. What can you not live without the most?
99. What do you enjoy doing over and over again?
100. When did you last laugh so much it hurt?
101. What is stopping you from living the life you want to live?

C:\xampp\htdocs\test\wp-content\plugins\lionel\admin\util\class-question-reader.php

<?php
/**
 * Reads the contents of a specified file and returns a random line from the
 * file.
 */
/**
 * Reads the contents of a specified file and returns a random line from the
 * file.
 *
 * This class is used to populate the contents of the meta box with questions
 * that prompt the user for ideas about which to write.
 *
 * Note this class is only for demo purposes. It has no error handling and
 * assumes the specified file always exists.
 */
class Question_Reader {
  /**
   * Retrieves a question from the specified file.
   *
   * @param  string $filename  The path to the file that contains the question.
   * @return string $question A single question from the specified file.
   */
  public function get_question_from_file($filename) {
    $question = '';
    $file_handle = $this->open($filename);
    $question    = $this->get_random_question($file_handle, $filename);
    $this->close($file_handle);
    return $question;
  }
  /**
   * Opens the file for reading and returns the resource to the file.
   *
   * @access private
   * @param  string $filename  The path to the file that contains the question.
   * @return resource          A resource to the file.
   */
  private function open($filename) {
    return fopen($filename, 'r');
  }
  /**
   * Closes the file that was read.
   *
   * @access private
   * @param  string $file_handle The resource to the file that was read.
   */
  private function close($file_handle) {
    fclose($file_handle);
  }
  /**
   * Opens the file for reading and returns the resource to the file.
   *
   * @access private
   * @param  string $file_handle The resource to the file that was read.
   * @param  string $filename    The path to the file containing the question.
   * @return string $question    The question to display in the meta box.
   */
  private function get_random_question($file_handle, $filename) {
    $questions = fread($file_handle, filesize($filename));
    $questions = explode("\n", $questions);
    // Look for a question until an empty string is no longer returned.
    $question = $questions[rand(0, 75)];
    while (empty($question)) {
      $question = $questions[rand(0, 75)];
    }
    return $question;
  }
}
?>

Không gian tên và autoload không phải là chủ đề thường được đề cập đến khi làm việc với các plugin của WordPress.

Một số liên quan đến cộng đồng xung quanh nó, một số liên quan đến các phiên bản PHP mà WordPress hỗ trợ, và một số chỉ đơn giản là liên quan đến thực tế rằng không nhiều người đang nói về nó.

Và một phần nào đó, điều này không sao cả.

Không gian tên cũng như autoload không phải là các chủ đề mà bạn nhất thiết cần dùng đến để tạo các plugin. Tuy nhiên, chúng có thể cung cấp một cách tốt hơn để tổ chức và cấu trúc code của bạn cũng như giảm thiểu số câu lệnh require, require_once, include, hoặc include_once mà plugin của bạn sử dụng.

Trong loạt bài này, chúng ta sẽ tìm hiểu một cách chính xác không gian tên của PHP là gì, tại sao chúng lại có ích, và cách sử dụng chúng. Sau đó, chúng ta sẽ tìm hiểu cách sử dụng autoload để tự động nạp các tập tin mà chúng ta cần mà không cần phải nạp chúng một cách thủ công trong code của chúng ta.

Trước khi Bắt đầu

Để bắt đầu, bạn sẽ cần các công cụ sau đây:

  • Môi trường phát triển cục bộ bao gồm PHP 5.6.20, máy chủ web Apache và máy chủ cơ sở dữ liệu MySQL.

  • Một thư mục chứa WordPress 4.6.

  • Một trình soạn thảo hay IDE mà bạn quen dùng để viết một plugin.

  • Kiến thức về WordPress Plugin API.

Một khi bạn đã có tất cả những điều đó, hãy bắt đầu xây dựng một plugin. Lưu ý rằng nếu bất kỳ điều gì ở trên có vẻ mới mẻ đối với bạn, thì đừng ngần ngại xem lại các hướng dẫn trước đây ở trên trang tiểu sử của tôi.

Hơn nữa, bạn có thể theo dõi tôi trên blog và/hoặc Twitter của tôi tại @tommcfarlin, nơi tôi nói về phát triển phần mềm trong ngữ cảnh của WordPress.

Bây giờ chúng ta hãy bắt đầu.

Những gì Chúng ta Sẽ Xây dựng

Trong loạt bài này, chúng ta sẽ xây dựng một plugin đơn giản chủ yếu để minh hoạ cách không gian tên và autoload hoạt động trong PHP. Nhưng để làm điều đó, hãy luôn giúp áp dụng các khái niệm theo hướng thực hành.

Với mục đích đó, chúng ta sẽ xây dựng một plugin giúp dễ dàng nạp các stylesheet và JavaScript trong plugin của chúng ta và hiển thị meta-box nhắc nhở người dùng bằng một câu hỏi để giúp gợi ý họ về những gì cần để viết blog.

Không, đây không phải là điều mà bạn muốn gửi tới WordPress Plugin Repository, cũng không phải là một thứ gì đó mà bạn có thể sử dụng bên ngoài demo cụ thể này. Nhưng hãy nhớ rằng, mục đích của loạt bài này là để minh hoạ không gian tên và autoload hoạt động như thế nào.

Và thông qua ví dụ này, chúng ta sẽ làm điều đó.

Xây dựng Plugin

Nếu bạn đã theo dõi bất kỳ hướng dẫn nào trước đây của tôi, thì bạn đã biết một trong những điều tôi muốn làm là lập kế hoạch cho những gì chúng ta sắp sửa xây dựng trước khi chúng ta nhảy vào viết bất kỳ code nào. Như vậy, đối với bước đầu tiên của plugin này, thì đây là những gì chúng ta sẽ cần làm:

  1. Định nghĩa một tập tin khởi động để khởi chạy plugin.

  2. Thiết lập một thư mục chứa tất cả các tập tin sẽ hiển thị meta-box.

  3. Tạo một thư mục để chứa lớp sẽ nạp các phụ thuộc của chúng ta.

  4. Chuẩn bị stylesheet và JavaScript cho plugin của chúng ta.

Nó có vẻ đơn giản, đúng không? Nếu không cũng đừng lo lắng. Tôi sẽ hướng dẫn bạn toàn bộ quá trình hoàn chỉnh với code, comment, ảnh chụp màn hình và giải thích.

Hãy bắt đầu thôi.

Tạo Thư mục cho Plugin

Ngay từ đầu, chúng ta đã biết rằng chúng ta sẽ cần một tập tin đóng vai trò như là một trình khởi động cho plugin. Chúng ta cũng biết rằng chúng ta sẽ cần một thư mục cho chức năng quản trị.

Đương nhiên, chúng ta có một tập tin rỗng và một thư mục admin. Hãy tiếp tục và thiết lập plugin này để nó xuất hiện bên trong ngữ cảnh của màn hình kích hoạt WordPress Plugin.

Để làm điều này, chúng ta cần phải thêm đoạn code sau đây vào đầu của tập tin plugin:

0102030405060708091011121314151617181920212223

<?php/** * The plugin bootstrap file * * This file is read by WordPress to generate the plugin information in the * plugin admin area. This file also includes all of the dependencies used by * the plugin, registers the activation and deactivation functions, and defines * a function that starts the plugin. * * @link http://.tutsplus.com/tutorials/using-namespaces-and-autoloading-in-wordpress-plugins-part-1 * @since 0.1.0 * @package tutsplus_namespace_demo * * @wordpress-plugin * Plugin Name: Tuts+ Namespace Demo * Plugin URI: http://.tutsplus.com/tutorials/using-namespaces-and-autoloading-in-wordpress-plugins-part-1 * Description: Learn how to use Namespaces and Autoloading in WordPress. * Version: 0.1.0 * Author: Tom McFarlin * Author URI: https://tommcfarlin.com/ * License: GPL-2.0+ * License URI: http://www.gnu.org/licenses/gpl-2.0.txt */

Tại thời điểm này, chúng ta có thể tiếp tục và bắt đầu định nghĩa lớp sẽ kết xuất meta-box của chúng ta trên trang Add New Post.Advertisement

Thêm một Meta-Box

Phần này của hướng dẫn này sẽ giả định rằng bạn đã nắm khá vững về việc tạo các meta-box. Nếu không, đừng ngần ngại xem lại các khái niệm trong loạt bài này và sau đó quay trở lại phần này khi đã xong.

Đầu tiên, hãy tạo một tập tin có tên là class-meta-box-display.php trong thư mục admin của plugin. Sẽ bao gồm các code sau đây. Hãy chắc chắn xem lại các comment ​​để đảm bảo bạn hiểu tất cả mọi thứ mà lớp này chịu trách nhiệm thực hiện.

0102030405060708091011121314151617181920212223

<?php/** * Defines the functionality required to render the content within the Meta Box * to which this display belongs. */ /** * Defines the functionality required to render the content within the Meta Box * to which this display belongs. * * When the render method is called, the contents of the string it includes * or the file it includes to render within the meta box. */class Meta_Box_Display { /** * Renders a single string in the context of the meta box to which this * Display belongs. */ public function render() { echo 'This is the meta box.'; }}

Từ code ở trên, bạn sẽ có thể biết chắc rằng lớp này chịu trách nhiệm hiển thị nội dung bên trong meta-box. Tuy nhiên, lúc này, chúng ta chỉ in ra một câu cho view.

Chúng ta sẽ thay đổi điều này sau trong hướng dẫn này.

Tiếp theo, chúng ta cần đưa ra một lớp đại diện cho chính meta-box. Vì vậy hãy tạo một tập tin class-meta-box.php trong thư mục admin của plugin. Dưới đây là code để thực hiện chính xác điều đó Một lần nữa, hãy xem lại code và sau đó tôi sẽ giải thích chuyện gì đang xảy ra bên dưới lớp:

0102030405060708091011121314151617181920212223242526272829303132333435363738394041424344454647484950

<?php/** * Represents a meta box to be displayed within the 'Add New Post' page. */ /** * Represents a meta box to be displayed within the 'Add New Post' page. * * The class maintains a reference to a display object responsible for * displaying whatever content is rendered within the display. */class Meta_Box { /** * A reference to the Meta Box Display. * * @access private * @var Meta_Box_Display */ private $display; /** * Initializes this class by setting its display property equal to that of * the incoming object. * * @param Meta_Box_Display $display Displays the contents of this meta box. */ public function __construct( $display ) { $this->display = $display; } /** * Registers this meta box with WordPress. * * Defines a meta box that will render inspirational questions at the top * of the sidebar of the 'Add New Post' page in order to help prompt * bloggers with something to write about when they begin drafting a post. */ public function init() { add_meta_box( 'tutsplus-post-questions', 'Inspiration Questions', array( $this->display, 'render' ), 'post', 'side', 'high' ); }}

Lớp này duy trì một thuộc tính duy nhất mà là một tham chiếu đến màn hình hiển thị (display) của nó. Điều này có nghĩa là lớp này chịu trách nhiệm định nghĩa meta-box (do đó, lần lượt gọi đối tượng display để kết xuất thông báo).

Display được duy trì như là một thuộc tính riêng tư (private) thiết lập trong hàm xây dựng. Meta-box không thật sự được định nghĩa cho đến khi phương thức init được gọi (chúng ta sẽ thấy nó sau trong trình khởi động của plugin).

Tại thời điểm này, chúng ta có mọi thứ chúng ta cần để hiển thị một meta-box thô sơ trong trang Add New Post. Nhưng trước tiên, chúng ta cần phải thiết lập trình khởi động cho plugin của chúng ta.

Trong các hướng dẫn trước, tôi đã làm điều này rất nhiều vì vậy tôi sẽ chỉ bao gồm code cần thiết (vì tôi đã định nghĩa header ở trên). Tôi đã thêm các comment, nhưng chắc chắn tôi cũng sẽ giải thích những gì đang xảy ra sau code.

Điều này đặc biệt hợp lý bởi vì autoload của chúng ta cuối cùng sẽ phủ định sự cần thiết đối với một số thứ bạn sắp sửa nhìn thấy.

010203040506070809101112131415161718192021

<?php // If this file is accessed directory, then abort.if ( ! defined( 'WPINC' ) ) { die;} // Include the files for rendering the display.include_once( 'admin/class-meta-box.php' );include_once( 'admin/class-meta-box-display.php' ); add_action( 'plugins_loaded', 'tutsplus_namespace_demo' );/** * Starts the plugin by initializing the meta box, its display, and then * sets the plugin in motion. */function tutsplus_namespace_demo() { $meta_box = new Meta_Box( new Meta_Box_Display() ); $meta_box->init();}

Trước tiên, chúng ta đảm bảo rằng tập tin này không thể truy cập trực tiếp và chỉ có thể chạy bởi chính WordPress.

Ví dụ 2:

Trước tiên, chúng ta đảm bảo rằng tập tin này không thể truy cập trực tiếp và chỉ có thể chạy bởi chính WordPress.

Tiếp theo, chúng ta include_once các lớp mà chúng ta đã tạo ra cho đến lúc này. Tiếp theo, chúng ta khởi tạo Meta_Box và truyền vào nó một đối tượng Meta_Box_Display trong hàm xây dựng của nó.

Cuối cùng, chúng ta gọi phương thức init nằm trong lớp Meta_Box.

Tại thời điểm này, chúng ta có một plugin hoạt động được, nhưng nó chưa thật sự làm bất cứ điều gì khác hơn là tạo ra một meta-box và hiển thị một chuỗi văn bản.

It nhất hãy là làm cho nó để hiển thị một số trích dẫn truyền cảm và hiển thị ngẫu nhiên từng cái một mỗi lần trang được tải.

Hiển thị Trích dẫn Truyền cảm

Tiếp theo, chúng ta sẽ cần tạo ra một lớp mà sẽ:

  1. Mở tập tin.

  2. Đọc một dòng ngẫu nhiên vào một chuỗi.

  3. Đóng tập tin.

  4. Trả về chuỗi cho hàm gọi.

Hãy tiếp tục và tạo ra lớp đó ngay bây giờ. Bởi vì đây là một tiện ích và nó sẽ được sử dụng ở phía quản trị của plugin, nên hãy tạo một thư mục util con của thư mục admin. Tiếp theo, hãy tạo một tập tin có tên là class-question-reader.php.

Chúng ta sẽ viết code cho lớp này trong giây lát nữa, nhưng quay trở lại tập tin khởi động của plugin và nhớ include tập tin này. Kết quả code sẽ giống như sau:

123456

<?php // Include the files for rendering the display.include_once( 'admin/class-meta-box.php' );include_once( 'admin/class-meta-box-display.php' );include_once( 'admin/util/class-question-reader.php' );

Như bạn có thể thấy, số lượng tập tin mà chúng ta phải tự include đang ngày càng dài hơn. Hãy tưởng tượng nếu chúng ta đang làm việc trên một plugin lớn! Tuy nhiên, chúng ta sẽ quay lại điều này sau trong loạt bài này.

Còn bây giờ, hãy chuyển sự chú ý của chúng ta trở lại với trình đọc câu hỏi. Code cho lớp sẽ giống như sau:

01020304050607080910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879

<?php/*** Reads the contents of a specified file and returns a random line from the* file.*/ /*** Reads the contents of a specified file and returns a random line from the* file.** This class is used to populate the contents of the meta box with questions* that prompt the user for ideas about which to write.** Note this class is only for demo purposes. It has no error handling and* assumes the specified file always exists.*/class Question_Reader { /** * Retrieves a question from the specified file. * * @param string $filename The path to the file that contains the question. * @return string $question A single question from the specified file. */ public function get_question_from_file( $filename ) { $question = ''; $file_handle = $this->open( $filename ); $question = $this->get_random_question( $file_handle, $filename ); $this->close( $file_handle ); return $question; } /** * Opens the file for reading and returns the resource to the file. * * @access private * @param string $filename The path to the file that contains the question. * @return resource A resource to the file. */ private function open( $filename ) { return fopen( $filename, 'r' ); } /** * Closes the file that was read. * * @access private * @param string $file_handle The resource to the file that was read. */ private function close( $file_handle ) { fclose( $file_handle ); } /** * Opens the file for reading and returns the resource to the file. * * @access private * @param string $file_handle The resource to the file that was read. * @param string $filename The path to the file containing the question. * @return string $question The question to display in the meta box. */ private function get_random_question( $file_handle, $filename ) { $questions = fread( $file_handle, filesize( $filename ) ); $questions = explode( "\n", $questions ); // Look for a question until an empty string is no longer returned. $question = $questions[ rand( 0, 75 ) ]; while ( empty( $question ) ) { $question = $questions[ rand( 0, 75 ) ]; } return $question; }}

Lưu ý rằng, code cho điều này là tương đối đơn giản, nhưng nếu bạn không nắm vững một số thao tác cơ bản trên tập tin trong PHP, thì dưới đây là những gì chúng ta đang làm:

  1. Chúng ta đang mở tập tin tin bằng fopen, nó sẽ cung cấp cho chúng ta một tài nguyên để đọc tập tin.

  2. Tiếp theo, chúng ta đang đọc nội dung của tập tin và sau đó lấy từng dòng của tập tin và ghi nó vào một chỉ mục của một mảng.

  3. Sau đó, chúng ta chọn một con số ngẫu nhiên từ mảng các câu hỏi và trả về cho phương thức gọi nó. Nếu nó trả về một chuỗi rỗng, chúng ta tìm kiếm một lần nữa cho đến khi một câu hỏi được xác định.

  4. Sau đó, chúng ta đóng tài nguyên trỏ đến tập tin.

Cuối cùng, để sử dụng lớp này, bạn chỉ cần khởi tạo nó, biết đường dẫn đến một tập tin chứa các câu hỏi, và sau đó gọi phương thức get_question_from_file.

Lưu ý: Lớp này chưa xử lý bất kỳ lỗi nào. Đó là một tiêu chuẩn thực hành khi làm việc với các tập tin. Ví dụ, chúng ta nên làm gì nếu tập tin không tồn tại? Chúng ta nên làm gì nếu nó không được định dạng đúng, hoặc nếu chúng ta không thể đóng tài nguyên thì sao?

Tất cả đều là những câu hỏi hay, nhưng chúng nằm ngoài phạm vi của hướng dẫn này. Tất cả những thông tin này có thể được tìm thấy trong hướng dẫn sử dụng PHP (và có thể là một số hướng dẫn khác trên Envato Tuts+).

Tuy nhiên, lúc này chúng ta quan tâm đến việc đọc một tập tin mà chúng ta biết là nó tồn tại và chúng ta quan tâm đến việc hiển thị các kết quả trong meta-box.

Đến lúc này chúng ta có được những gì rồi

Tại thời điểm này, chúng ta có thể bắt đầu kết hợp tất cả mọi thứ lại với nhau. Giả sử chúng ta đã thực hiện tất cả các bước một cách chính xác, chúng ta có thể truyền một đối tượng Question_Reader vào Meta_Box_Display, đặt một câu hỏi, và sau đó hiển thị nó trong meta-box.

Đầu tiên, hãy cập nhật tập tin khởi động:

010203040506070809101112

<?php function tutsplus_namespace_demo() { $meta_box = new Meta_Box( new Meta_Box_Display( new Question_Reader() ) ); $meta_box->init();}

Trong code ở trên, hãy chú ý rằng Meta_Box_Display hiện chấp nhận một đối tượng Question_Reader trong hàm xây dựng của nó. Điều này hàm ý rằng chúng ta cần phải đưa ra một thuộc tính mới, chúng ta sẽ làm điều đó ngay bây giờ:

0102030405060708091011121314151617181920212223242526272829303132333435363738394041424344

<?php/** * Defines the functionality required to render the content within the Meta Box * to which this display belongs. */ /** * Defines the functionality required to render the content within the Meta Box * to which this display belongs. * * When the render method is called, the contents of the string it includes * or the file it includes to render within the meta box. */class Meta_Box_Display { /** * A reference to the object responsible for retrieving a question to display. * * @access private * @var Question_Reader $question_reader */ private $question_reader; /** * Initializes the class by setting the question reader property. * * @param Question_Reader $question_reader The object for retrieving a question. */ public function __construct( $question_reader ) { $this->question_reader = $question_reader; } /** * Renders a single string in the context of the meta box to which this * Display belongs. */ public function render() { $file = dirname( __FILE__ ) . '/data/questions.txt'; $question = $this->question_reader->get_question_from_file( $file ); echo wp_kses( $question ); }}

Lưu ý rằng tập tin này sử dụng đường dẫn tới các câu hỏi mà tập tin được thêm vào thư mục con data. Bên cạnh đường dẫn được viết trực tiếp, lớp này còn phụ thuộc vào một đối tượng Question_Reader.

Đối với mục đích của demo mà chúng ta đang hướng đến (cụ thể là không gian tên và autoload), điều đó ổn. Trong một dự án tương lai, chúng ta muốn các dự án có ít sự móc nối giữa chúng. Có lẽ đây sẽ là một chủ đề cho một hướng dẫn trong tương lai.

Tuy nhiên, vấn đề chủ yếu từ code ở trên là lớp Meta_Box_Display bây giờ có thể hiển thị một câu hỏi cho người dùng.

Hơn nữa, lưu ý việc sử dụng wp_kses để làm sạch dữ liệu trước khi trình bày nó cho người dùng.

Làm mới lại trang Add New Post sẽ hiển thị cho bạn một hình ảnh như sau:

Và nếu bạn làm mới trang thì bạn có thể thấy các câu hỏi mới đang được tải.Advertisement

Từ đây Chúng ta Làm gì Tiếp theo?

Đương nhiên, chúng ta chưa thật sự đụng đến các chủ đề về không gian tên và autoload, nhưng không sao cả! Điều quan trọng là chúng ta đặt nền móng cho một plugin mà không sử dụng chúng. Bằng cách đó, khi chúng ta tiến hành cài đặt chúng, chúng ta có thể thấy được những lợi ích mà chúng mang đến.

Hơn nữa, chúng ta vẫn còn một số việc cần làm: Chúng ta cần giới thiệu về JavaScript, CSS và Asset Loader. Điều này sẽ cho phép chúng ta thậm chí có được một bức tranh rộng hơn về việc đóng gói các tập tin của chúng ta vào các không gian tên như thế nào là có lợi.

Hãy nhớ rằng, bạn có thể tìm thấy tất cả các hướng dẫn trước đây trên trang tiểu sử của tôi và bạn có thể theo dõi tôi trên blog hoặc trên Twitter của tôi.

Như thường lệ, nếu bạn đang tìm kiếm các tiện ích khác để giúp bạn xây dựng bộ công cụ đang tăng trưởng của bạn cho WordPress hoặc code ví dụ để nghiên cứu và trở nên thành thạo hơn trong WordPress, thì đừng quên xem qua những gì chúng tôi có sẵn trên Envato Market.

Như đã nói, chúng ta sẽ có một phiên bản hoạt động của plugin sẵn sàng để tải xuống bắt đầu trong hướng dẫn tiếp theo của loạt bài này. Nếu bạn muốn sử dụng code trong hướng dẫn ở trên, đừng ngần ngại thử và làm theo. Hơn nữa, đừng ngại đặt bất kỳ câu hỏi nào trong phần bình luận.

Last updated