Skip to content

Instantly share code, notes, and snippets.

@ZachWatkins
Forked from tommcfarlin/00-repository.php
Created November 14, 2021 06:07
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 ZachWatkins/e67a0bf6f0f606247af8557d3de1a8be to your computer and use it in GitHub Desktop.
Save ZachWatkins/e67a0bf6f0f606247af8557d3de1a8be to your computer and use it in GitHub Desktop.
[Software Development] Using The Repository Pattern in WordPress
<?php
/**
* Serves as a registry for all objects that need to be accessed globally throughout the
* plugin.
*/
class Registry
{
/**
* @var array The array used to the the various objects that will be used in the plugin.
*/
private $storage;
/**
* Initializes the plugin by creating an instance of an empty array.
*/
public function __construct()
{
$this->storage = [];
}
/**
* Adds an instance of a class to the registry's storage array using the given key
*
* @param string $id The ID of the object to be used to retrieve it later in the plugin.
* @param mixed $class An instance of the class that will be associated with the specified key.
*/
public function add($id, $class)
{
$this->storage[$id] = $class;
}
/**
* @param string $id The ID of the object to retrieve from the repository.
* @return mixed $class An instance of the class associated with the specified key (or null if it doesn't exist).
*/
public function get($id)
{
return array_key_exists($id, $this->storage) ? $this->storage[$id] : null;
}
}
<?php
/**
* Creates a Registry using the Registry Design Pattern to store objects
* that can be used throughout the plugin.
*
*/
$registry = new Registry();
add_filter('acmeRegistry', function () use ($registry) {
return $registry;
});
<?php
/**
* Get an reference to the repository and add an instance of a
* PostManager to it. The PostManager is a class that allows us
* to manipulate posts.
*/
$this->registry = apply_filters('acmeRegistry', null);
$this->registry->add('postManager', new PostManager());
<?php
/**
* Get an reference to the repository, get a reference to the PostManager
* then you can begin working with it.
*/
$this->registry = apply_filters('acmeRegistry', null);
$this->registry->add('postManager', new PostManager());
// An example call that you can make to set the title of the post.
$postManager->updateTitle('This Is the New Title');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment