Registering Action Hooks - 3ev/wordpress-core GitHub Wiki
Registering action hooks with Wordpress Core provides a better separation of concerns than Wordpress's built in add_action() method.
###The config file
Your plugin's actions should all be registered in the config/actions.php PHP file inside your plugin's root folder. This file should return a simple PHP hash, with each key being an action name and each value being either a fully-qualified class name of an action provider, or an inline callback closure (although this is not recommended).
An example file might look like:
<?php
return array(
'init' => 'MyPluginVendor\Action\MyInitProvider',
'publish_post' => function ($hook, $function_to_add, $priority, $accepted_args) {
// Handle action here
}
);
###Using an action provider
An action provider is a PHP class that extends Tev\Plugin\Action\AbstractProvider. The provider at a minimum needs to provide an action() method, which accepts the parameters expected by the action you're hooking into. This method will contain all of the logic need to handle your action.
An example of a provider is:
config/actions.php:
<?php
return array(
'save_post' => 'MyPluginVendor\Action\MySavePostProvider'
);
src/MyPluginVendor/Action/MySavePostProvider.php:
<?php
namespace MyPluginVendor\Action;
use Tev\Plugin\Action\AbstractProvider;
class MySavePostProvider extends AbstractProvider
{
public function action($postId, $post, $update)
{
$postModel = $this->app->fetch('post_factory')->create($post);
// Do something with post model
}
/**
* Configure the callback priority.
*
* You only need to provided this function if you don't want to use the default (10).
*
* @return int
*/
public function priority()
{
return 12;
}
/**
* Configure the number of arguments expected to `action()`.
*
* Depends on hook. You only need to provided this function if
* you don't want to use the default (1).
*
* @return int
*/
public function numArgs()
{
return 3;
}
}
As you can see from the example, the DI container is available at $this->app. You also have a renderer available to you at $this->renderer, which is configured to use the src/views/ directory in the same way as the shortcode renderer.
###Using a callback function
Although it's recommended to use a provider class, you can also register an action hook inline with a callback function.
For example:
config/actions.php:
<?php
return array(
'save_post' => function ($post_id) {
// Handle action here
}
);
Note: Using an inline callback means that you can't control the number of expected arguments or the hook priority. You also don't have access to a view renderer, although you can use the DI container with via the tev_app() helper.