Components

In HivePress, components are PHP classes that are used to group actions, filters, and helper functions. For example, the Router component contains all the callbacks and helper functions for managing URLs and redirects.

If the component class has a public method, you can use it as a helper and call it from anywhere via the hivepress function and the component name. For example, the Router component has the get_url method, so it can be called this way:

$url = hivepress()->router->get_url( 'my_custom_route' );

Components are also useful for adding action and filter callbacks. The class constructor is used for attaching callbacks to hooks with the add_filter and add_action functions, while the public class methods are used as callbacks.

Creating components

If you are developing a custom HivePress extension, you should create a default component for it. To do this, create a new class-{extension-name}.php file (use lowercase letters, numbers, and hyphens only) in the includes/components extension subdirectory and HivePress will load it automatically.

Then, define the component PHP class. The class name should be based on the file name but with underscores instead of hyphens and no lowercase restriction (e.g. Foo_Bar class for the class-foo-bar.php file). Pick a name that is unique enough to avoid conflicts with other HivePress components.

<?php
namespace HivePress\Components;

use HivePress\Helpers as hp;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

final class Foo_Bar extends Component {
	public function __construct( $args = [] ) {

		// Attach functions to hooks here (e.g. add_action, add_filter).
		add_action( 'template_redirect', [ $this, 'redirect_page' ] );

		parent::__construct( $args );
	}

	public function redirect_page() {
		// Implement the attached function here.
	}

	public function do_something() {
		// Implement the helper function here.
	}
}

The code above defines a new Foo_Bar component with a single action callback executed on every page load and a public method that can be called from anywhere in the code:

hivepress()->foo_bar->do_something();

Similarly, you can implement the callbacks and helpers for your extension within a single file.

Last updated