Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Last active February 21, 2024 21:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save igorbenic/302af57d0a1b53da7f6bef58a46c8ffe to your computer and use it in GitHub Desktop.
Save igorbenic/302af57d0a1b53da7f6bef58a46c8ffe to your computer and use it in GitHub Desktop.
How to use PHP Namespaces in WordPress Plugins | https://www.ibenic.com/php-namespaces-wordpress-plugins
<?php
namespace My_Plugin\API;
/**
* API Functions
*/
if( ! defined( 'ABSPATH' ) ) {
return;
}
/**
* Get all users from an API
* @return array
*/
function get_users() {
$api_key = ''; //Should have a way to retrieve the api key.
// API class is under namespace My_Plugin\API so we can call it directly.
$api = new API();
$users = $api->call( 'get_users_url', array( 'api_key' => $api_key ), 'get' );
// Performs an API call.
return $users;
}
<?php
namespace My_Plugin\API;
/**
* API class
*/
if( ! defined( 'ABSPATH' ) ) {
return;
}
class API {
/**
* Making a call
* @param string $url
* @param array $args
* @param string $method
* @return WP_Error|WP_Http
*/
public function call( $url = '', $args = array(), $method = 'post' ) {
if( 'post' === $method ) {
return wp_remote_post( $url, $args );
} else {
return wp_remote_get( $url, $args );
}
}
}
<?php
namespace My_Plugin\DB;
/**
* Database Functions
*/
if( ! defined( 'ABSPATH' ) ) {
return;
}
/**
* Get all users from a database
* @return array
*/
function get_users() {
// Perform a database call to get users
return array();
}
<?php
namespace My_Plugin\DB;
use My_Plugin\API\API;
<?php
/**
* Showing how to call functions from others
* @return API
*/
function populate_db_from_api() {
$api = new API();
return $api;
}
<?php
// ...
class My_Plugin {
/**
* Loading all dependencies
* @return void
*/
public function load() {
include_once 'includes/api/class-api.php';
include_once 'includes/db/functions.php';
include_once 'includes/api/functions.php';
}
}
<?php
// ...
/**
* Loading my plugin
* @return void
*/
function my_plugin_load() {
$pg = new My_Plugin();
$pg->load();
}
// We need to call the function with the namespace
add_action( 'plugins_loaded', 'My_Plugin\my_plugin_load' );
<?php
/**
* Plugin Name: Namespaces in WordPress
* Plugin Description: A showcase plugin so you can learn how to use namespaces in your projects.
*/
namespace My_Plugin;
if( ! defined( 'ABSPATH' ) ) {
return;
}
class My_Plugin {
}
<?php
// ...
class My_Plugin {
// ...
/**
* Dummy method to check if we should use api or database call
* @return bool
*/
public function use_api() {
// check for api key or similar.
return false;
}
/**
* Get users
* @return void
*/
public function get_users() {
if( $this->use_api() ) {
return API\get_users();
} else {
return DB\get_users();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment