国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
(Un)Designed Programming
Great moments in API design: jQuery
WordPress API
solution
1. Shortcuts for common tasks
2: Unpredictable input, predictable output
3。合理的默認值
先設(shè)計,后構(gòu)建
保持直覺
結(jié)論
Home CMS Tutorial WordPress Enhance WordPress: Build improved APIs and libraries

Enhance WordPress: Build improved APIs and libraries

Sep 02, 2023 am 11:33 AM

增強 WordPress:打造改進的 API 和庫

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.

(Un)Designed 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.

Great moments in API design: jQuery

??>

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();

WordPress API

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.


solution

To speed up my work and reduce repetitive tasks, I created libraries to handle the commands and customizations I always needed.

1. Shortcuts for common tasks

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() ) . '" />';

2: Unpredictable input, predictable output

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?

3。合理的默認值

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;
    
}

我們再次進行了簡化,因此用戶無需發(fā)送帖子,甚至無需發(fā)送帖子 ID。在循環(huán)中時,所需要做的就是:

echo '<img src="'.get_thumbnail_src().'" />';

我們的函數(shù)將默認為當(dāng)前帖子的 ID。這正在變成一個非常有價值的功能。為了確保它能很好地發(fā)揮作用,讓我們將它包裝在一個類中,這樣它就不會污染全局命名空間。

/*
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。我將其設(shè)為公共靜態(tài)函數(shù),因為我希望它可以在任何地方訪問,并且它不會改變:輸入或執(zhí)行不會更改函數(shù)或?qū)ο蟆?

該函數(shù)的最終調(diào)用是:

echo '<img src="'.JaredsTools::get_thumbnail_src().'">';

先設(shè)計,后構(gòu)建

讓我們繼續(xù)處理更復(fù)雜的需求。當(dāng)我編寫插件時,我發(fā)現(xiàn)我總是需要生成不同類型的錯誤和/或更新消息。

但是基于事件的語法一直困擾著我:

add_action( 'admin_notices', 'show_my_notice');
functon show_my_notice(){
    echo '<div class="updated"><p>Your thing has been updated</p></div>';
}

WordPress 遵循這種基于事件的架構(gòu)有很多充分的理由。但這并不直觀,除非您想坐下來記住不同的過濾器和操作。

讓我們將此匹配作為最簡單的用例:我需要顯示管理員通知。我喜歡首先設(shè)計這個 API:我找出在代碼中引用該函數(shù)的最佳方式。我希望它讀起來像這樣:

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");
    }
}

一旦我設(shè)計了端點,我就可以滿足設(shè)計要求:

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>';
        });
    }
}

好多了!現(xiàn)在我不需要創(chuàng)建所有這些額外的函數(shù)或記住瘋狂的鉤子名稱。在這里,我使用 PHP 匿名函數(shù)(也稱為“閉包”),它讓我們可以將函數(shù)直接綁定到操作或過濾器。

這可以讓您避免在文件中出現(xiàn)大量額外的函數(shù)。 use 命令讓我們將參數(shù)從父函數(shù)傳遞到子閉包中。

保持直覺

現(xiàn)在另一位同事打電話給您。她不知道為什么她的管理通知沒有變成紅色:

JaredsTools::show_admin_notice("Error updating your thing", "red");

這是因為她正在發(fā)送“紅色”(她希望將盒子變成紅色),而實際上她應(yīng)該發(fā)送觸發(fā)紅色的名稱。但為什么不讓它變得更容易呢?

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>';
    });
}

我們現(xiàn)在已經(jīng)接受了更多的用戶容忍度,這將使我們在幾個月后回來使用它時更容易分享。


結(jié)論

在構(gòu)建了其中一些之后,以下是我學(xué)到的一些原則,這些原則使這些原則對我和我的團隊真正有用。

1.首先進行設(shè)計,讓函數(shù)的構(gòu)建符合人們想要使用它的方式。

2. 拯救你的鍵盤!為常見任務(wù)創(chuàng)建快捷方式。

3. 提供合理的默認值。

4. 保持最小化。讓您的庫來處理處理。

5. 對輸入要寬容,對輸出要精確。

6. 也就是說,使用盡可能少的函數(shù)參數(shù),最多四個是一個很好的參數(shù)。之后,您應(yīng)該將其設(shè)為選項數(shù)組。

7. 將您的庫組織成單獨的類,以涵蓋不同的領(lǐng)域(管理、圖像、自定義帖子等)。

8. 包含示例代碼的文檔。

在 Upstatement,我們的 Timber 庫使構(gòu)建主題變得更加容易,而 Jigsaw 提供了節(jié)省時間的快捷方式來自定義每個安裝。

這些工具節(jié)省的時間讓我們可以花更多時間構(gòu)建每個網(wǎng)站或應(yīng)用程序的新的和創(chuàng)新的部分。通過執(zhí)行深奧的命令(例如向管理帖子表添加一列)并制作簡單的界面:我們公司的任何設(shè)計師或開發(fā)人員都可以使用與專業(yè) WordPress 開發(fā)人員相同的能力完全自定義每個網(wǎng)站。

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use the WordPress testing environment How to use the WordPress testing environment Jun 24, 2025 pm 05:13 PM

Use WordPress testing environments to ensure the security and compatibility of new features, plug-ins or themes before they are officially launched, and avoid affecting real websites. The steps to build a test environment include: downloading and installing local server software (such as LocalWP, XAMPP), creating a site, setting up a database and administrator account, installing themes and plug-ins for testing; the method of copying a formal website to a test environment is to export the site through the plug-in, import the test environment and replace the domain name; when using it, you should pay attention to not using real user data, regularly cleaning useless data, backing up the test status, resetting the environment in time, and unifying the team configuration to reduce differences.

How to use Git with WordPress How to use Git with WordPress Jun 26, 2025 am 12:23 AM

When managing WordPress projects with Git, you should only include themes, custom plugins, and configuration files in version control; set up .gitignore files to ignore upload directories, caches, and sensitive configurations; use webhooks or CI tools to achieve automatic deployment and pay attention to database processing; use two-branch policies (main/develop) for collaborative development. Doing so can avoid conflicts, ensure security, and improve collaboration and deployment efficiency.

How to create a simple Gutenberg block How to create a simple Gutenberg block Jun 28, 2025 am 12:13 AM

The key to creating a Gutenberg block is to understand its basic structure and correctly connect front and back end resources. 1. Prepare the development environment: install local WordPress, Node.js and @wordpress/scripts; 2. Use PHP to register blocks and define the editing and display logic of blocks with JavaScript; 3. Build JS files through npm to make changes take effect; 4. Check whether the path and icons are correct when encountering problems or use real-time listening to build to avoid repeated manual compilation. Following these steps, a simple Gutenberg block can be implemented step by step.

How to set up redirects in WordPress htaccess How to set up redirects in WordPress htaccess Jun 25, 2025 am 12:19 AM

TosetupredirectsinWordPressusingthe.htaccessfile,locatethefileinyoursite’srootdirectoryandaddredirectrulesabovethe#BEGINWordPresssection.Forbasic301redirects,usetheformatRedirect301/old-pagehttps://example.com/new-page.Forpattern-basedredirects,enabl

How to flush rewrite rules programmatically How to flush rewrite rules programmatically Jun 27, 2025 am 12:21 AM

In WordPress, when adding a custom article type or modifying the fixed link structure, you need to manually refresh the rewrite rules. At this time, you can call the flush_rewrite_rules() function through the code to implement it. 1. This function can be added to the theme or plug-in activation hook to automatically refresh; 2. Execute only once when necessary, such as adding CPT, taxonomy or modifying the link structure; 3. Avoid frequent calls to avoid affecting performance; 4. In a multi-site environment, refresh each site separately as appropriate; 5. Some hosting environments may restrict the storage of rules. In addition, clicking Save to access the "Settings>Pinned Links" page can also trigger refresh, suitable for non-automated scenarios.

How to send email from WordPress using SMTP How to send email from WordPress using SMTP Jun 27, 2025 am 12:30 AM

UsingSMTPforWordPressemailsimprovesdeliverabilityandreliabilitycomparedtothedefaultPHPmail()function.1.SMTPauthenticateswithyouremailserver,reducingspamplacement.2.SomehostsdisablePHPmail(),makingSMTPnecessary.3.SetupiseasywithpluginslikeWPMailSMTPby

How to make a WordPress theme responsive How to make a WordPress theme responsive Jun 28, 2025 am 12:14 AM

To implement responsive WordPress theme design, first, use HTML5 and mobile-first Meta tags, add viewport settings in header.php to ensure that the mobile terminal is displayed correctly, and organize the layout with HTML5 structure tags; second, use CSS media query to achieve style adaptation under different screen widths, write styles according to the mobile-first principle, and commonly used breakpoints include 480px, 768px and 1024px; third, elastically process pictures and layouts, set max-width:100% for the picture and use Flexbox or Grid layout instead of fixed width; finally, fully test through browser developer tools and real devices, optimize loading performance, and ensure response

How to integrate third-party APIs with WordPress How to integrate third-party APIs with WordPress Jun 29, 2025 am 12:03 AM

Tointegratethird-partyAPIsintoWordPress,followthesesteps:1.SelectasuitableAPIandobtaincredentialslikeAPIkeysorOAuthtokensbyregisteringandkeepingthemsecure.2.Choosebetweenpluginsforsimplicityorcustomcodeusingfunctionslikewp_remote_get()forflexibility.

See all articles