Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active Oct 31, 2018
Embed
What would you like to do?
[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');
@ATLowther

This comment has been minimized.

Copy link

@ATLowther ATLowther commented Oct 31, 2018

Hey Tom,

Where are you retrieving and storing the object to $postManager?

/**
 * 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);
$postManager = $this->registry->get('postManager');

//An example call that you can make to set the title of the post.
$postManager->updateTitle('This Is the New Title');

This is how I would think you'd get access to the registry item based on the class definitions. I'm not familiar enough with PHP to understand how it would function otherwise. Is this a default behavior that I am not understanding?

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment