Skip to content

Instantly share code, notes, and snippets.

@chrisguitarguy
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisguitarguy/80f5078e653e738c2f9f to your computer and use it in GitHub Desktop.
Save chrisguitarguy/80f5078e653e738c2f9f to your computer and use it in GitHub Desktop.
Some example code for a blog post on PMG.co
<?php
function pmg_exampletheme_get_field($field)
{
if (!function_exists('get_field')) {
return null;
}
return get_field($field);
}
<?php
function pmg_exampletheme_get_field($field)
{
if (!function_exists('get_field')) {
throw new \LogicException('The Advanced Custom Fields Plugin is Not Loaded');
}
return get_field($field);
}
<?php
// in a theme file
do_action('pmg_exampletheme_some_action', $post);
// in a plugin
add_action('pmg_exampletheme_some_action', 'pmg_exampleplugin_some_action');
function pmg_examplepluing_some_action($post)
{
// do stuff with $post to create some nice display
}
<?php
namespace PMG\ExampleCustomer;
/**
* An API class for fetching custom metadata for a given customer post type.
*/
final class CustomerMeta
{
const WEBSITE_LINK = '_pmg_examplecustomer_websitelink';
/**
* The customer's post ID
*
* @var int
*/
private $postId;
public function __construct($postId)
{
$this->postId = $postId;
}
/**
* Get the link to the customer's home page.
*
* @return string
*/
public function getWebsiteLink()
{
return get_post_meta($this->postId, self::WEBSITE_LINK, true);
}
// ...
}
<?php
final class Customers
{
private $cache = [];
private static $ins = null;
public function __construct()
{
$this->hasPlugin = class_exists('PMG\\ExampleCustomer\\CustomerMeta');
}
// if you want to share the same instance...
public static function instance()
{
if (!self::$ins) {
self::$ins = new self();
}
return self::$ins;
}
public function getWebsiteLink($postId)
{
$customer = $this->loadCustomer($postId);
return $customer ? $customer->getWebsiteLink($postId) : null;
}
private function loadCustomer($postId)
{
if (!$this->hasPlugin) {
return null;
}
if (!isset($this->cache[$postId])) {
$this->cache[$postId] = new \PMG\ExampleCustomer\CustomerMeta($postId);
}
return $this->cache[$postId];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment