It feels like everything we come into contact with is carefully designed: website, phone number, subway map, etc. Even things we used to take for granted: thermostats, smoke detectors, and car dashboards now receive careful user experience treatment.
Design is more than just look and feel: it also needs to consider the various ways users need to interact with our devices/tools/screens/objects.
This also applies to programming.
Programming languages are a large and complex world. Even PHP, which many programming snobs consider too "simple", is actually a fairly complex combination of functions and classes that behave in very inconsistent ways.
Over the years, the syntax, methods, and naming have evolved across millions of different users and applications. Most tend to reflect the underlying construction inside - not necessarily how you want to use it.
When I started writing JavaScript around 2006, things were a mess. Here's how I find a tag with a specific class and move it around the DOM:
var uls = getElementsByTagName("ul"); var classToSearch = "foods"; for (var i = 0; i < uls.length; i++) { var classes = uls[i].getClasses(); for (var j = 0; j < classes.length; j++){ if (classes[j] == classToSearch){ myUL = uls[i]; } } } var $li = document.createElement('li'); $li.innerHTML = 'Steak'; myUL.innerHTML += $li;
Finish!
jQuery makes JavaScript fun again. In the late 2000s, the impact was so huge that I remember my dad asking me about “something weird” he’d read about in the Wall Street Journal. But despite its huge effect, jQuery doesn't add any "new functionality" to JavaScript. It just breaks down what developers have to do into very clear patterns.
Instead of reinventing how to find content on a page, they leveraged something people already knew: CSS selectors. Then it's just a matter of gathering a bunch of common operations and organizing them into dozens of functions. Let's try the previous example again, now using jQuery:
var $li = $('<li>Steak</li>'); $("ul.foods").append($li);
In 2006, I bought a 680 page Ajax book. With jQuery's excellent API, it's almost superseded by this:
$.post();
While API has come to stand for "third-party services," it simply means a programming interface that talks to a system. Just like the Twitter API or the Facebook API, the WordPress API also exists. You wouldn't do a raw database query to create a post, right? You use wp_insert_post
.
But many design holes plague the WordPress API. You might use get_the_title
but get_the_permalink
will generate an error if you use get_permalink
. Hey, when you have a decades-long open source project involving thousands of people's code and millions of users: you're going to encounter some quirks.
You can save a lot of time by masking these quirks and writing according to the habits and behaviors of the programmer you're writing for (which is probably you). This is where you can design the right interface for programming the plugins and themes you use every day.
To speed up my work and reduce repetitive tasks, I created libraries to handle the commands and customizations I always needed.
Take the source of getting the post thumbnail as an example. It turns out WordPress has no built-in functionality to get thumbnails based on post IDs (only attachment IDs).
This means I often find myself doing this:
$thumb_id = get_post_thumbnail_id( get_the_ID() ); $src = wp_get_attachment_thumb_url( $thumb_id ); echo '<img alt="" src="' . $src . '" />';
But there must be a better way!
function get_thumbnail_src( $post ){ $thumb_id = get_post_thumbnail_id( $post ); $src = wp_get_attachment_thumb_url( $thumb_id ); return $src; } echo '<img alt="" src="' . get_thumbnail_src( get_the_ID() ) . '" />';
much better! In fact, you find yourself using it all the time and then sharing it with other developers in the company.
Your friend is in trouble, so he calls you to debug, and you see:
echo '<img src="' . get_thumbnail_src( get_post() ) . '">';
It seems he accidentally used get_post
instead of get_the_ID
. You yelled at him. But wait, why notmake it more acceptable?
Maybe we can adjust our function so that it can take a WP_Post
object and still give the user what they expect. Let's get back to the function:
function get_thumbnail_src( $post ){ if ( is_object( $post ) && isset( $post->ID ) ){ $post = $post->ID; } else if ( is_array( $post ) && isset( $post['ID'] ) ) { $post = $post['ID']; } $thumb_id = get_post_thumbnail_id( $post ); $src = wp_get_attachment_thumb_url( $thumb_id ); return $src; }
So if they send WP_Post
objects or an array, your function can still help them get what they need. This is an important part of a successful API: hiding messy internals. You can make separate functions for
get_thumbnail_src_by_post_id and
get_thumbnail_src_by_wp_post_object.
In fact, it may be preferable for more complex conversions, but you can simplify the interface by routing individual functions to the correct subroutines. No matter what the user sends, this function will always return the string of the image source.
Let's move on: What if they send nothing?
function get_thumbnail_src( $post = false ) { if ( false === $post ) { $post = get_the_ID(); } else if ( is_object( $post ) && isset( $post->ID ) ) { $post = $post->ID; } else if ( is_array( $post ) && isset( $post['ID'] ) ) { $post = $post['ID']; } $thumb_id = get_post_thumbnail_id( $post ); $src = wp_get_attachment_thumb_url( $thumb_id ); return $src; }
我们再次进行了简化,因此用户无需发送帖子,甚至无需发送帖子 ID。在循环中时,所需要做的就是:
echo '<img src="'.get_thumbnail_src().'" />';
我们的函数将默认为当前帖子的 ID。这正在变成一个非常有价值的功能。为了确保它能很好地发挥作用,让我们将它包装在一个类中,这样它就不会污染全局命名空间。
/* Plugin Name: JaredTools Description: My toolbox for WordPress themes. Author: Jared Novack Version: 0.1 Author URI: http://upstatement.com/ */ class JaredsTools { public static function get_thumbnail_src( $post = false ) { if (false === $post ) { $post = get_the_ID(); } else if ( is_object( $post ) && isset( $post->ID ) ) { $post = $post->ID; } else if ( is_array( $post ) && isset( $post['ID'] ) ) { $post = $post['ID']; } $thumb_id = get_post_thumbnail_id( $post ); $src = wp_get_attachment_thumb_url( $thumb_id ); return $src; } }
并且请不要在您的类前面添加 WP
。我将其设为公共静态函数,因为我希望它可以在任何地方访问,并且它不会改变:输入或执行不会更改函数或对象。
该函数的最终调用是:
echo '<img src="'.JaredsTools::get_thumbnail_src().'">';
让我们继续处理更复杂的需求。当我编写插件时,我发现我总是需要生成不同类型的错误和/或更新消息。
但是基于事件的语法一直困扰着我:
add_action( 'admin_notices', 'show_my_notice'); functon show_my_notice(){ echo '<div class="updated"><p>Your thing has been updated</p></div>'; }
WordPress 遵循这种基于事件的架构有很多充分的理由。但这并不直观,除非您想坐下来记住不同的过滤器和操作。
让我们将此匹配作为最简单的用例:我需要显示管理员通知。我喜欢首先设计这个 API:我找出在代码中引用该函数的最佳方式。我希望它读起来像这样:
function thing_that_happens_in_my_plugin($post_id, $value){ $updated = update_post_meta($post_id, $value); if ($updated){ JaredsTools::show_admin_notice("Your thing has been updated") } else { JaredsTools::show_admin_notice("Error updating your thing", "error"); } }
一旦我设计了端点,我就可以满足设计要求:
class JaredsTools { public static function show_admin_notice($message, $class = 'updated'){ add_action('admin_notices', function() use ($message, $class){ echo '<div class="'.$class.'"><p>'.$message.'</p></div>'; }); } }
好多了!现在我不需要创建所有这些额外的函数或记住疯狂的钩子名称。在这里,我使用 PHP 匿名函数(也称为“闭包”),它让我们可以将函数直接绑定到操作或过滤器。
这可以让您避免在文件中出现大量额外的函数。 use
命令让我们将参数从父函数传递到子闭包中。
现在另一位同事打电话给您。她不知道为什么她的管理通知没有变成红色:
JaredsTools::show_admin_notice("Error updating your thing", "red");
这是因为她正在发送“红色”(她希望将盒子变成红色),而实际上她应该发送触发红色的类名称。但为什么不让它变得更容易呢?
public static function show_notice( $message, $class = 'updated' ) { $class = trim( strtolower( $class ) ); if ( 'yellow' == $class ) { $class = 'updated'; } if ('red' == $class ) { $class = 'error'; } add_action( 'admin_notices', function() use ( $text, $class ) { echo '<div class="'.$class.'"><p>' . $text . '</p></div>'; }); }
我们现在已经接受了更多的用户容忍度,这将使我们在几个月后回来使用它时更容易分享。
在构建了其中一些之后,以下是我学到的一些原则,这些原则使这些原则对我和我的团队真正有用。
1.首先进行设计,让函数的构建符合人们想要使用它的方式。
2. 拯救你的键盘!为常见任务创建快捷方式。
3. 提供合理的默认值。
4. 保持最小化。让您的库来处理处理。
5. 对输入要宽容,对输出要精确。
6. 也就是说,使用尽可能少的函数参数,最多四个是一个很好的参数。之后,您应该将其设为选项数组。
7. 将您的库组织成单独的类,以涵盖不同的领域(管理、图像、自定义帖子等)。
8. 包含示例代码的文档。
在 Upstatement,我们的 Timber 库使构建主题变得更加容易,而 Jigsaw 提供了节省时间的快捷方式来自定义每个安装。
这些工具节省的时间让我们可以花更多时间构建每个网站或应用程序的新的和创新的部分。通过执行深奥的命令(例如向管理帖子表添加一列)并制作简单的界面:我们公司的任何设计师或开发人员都可以使用与专业 WordPress 开发人员相同的能力完全自定义每个网站。
The above is the detailed content of Enhance WordPress: Build improved APIs and libraries. For more information, please follow other related articles on the PHP Chinese website!