Skip to content
This repository has been archived by the owner on Jun 3, 2021. It is now read-only.

Method Chaining

James Burke edited this page Jun 19, 2019 · 2 revisions

Using the callable method, you can easily create a fork during a method chain. This means you can conditionally execute code when you need it, rather than before the return statement begins.

For example, consider an component where you want to set the theme conditionally. You may do something like this,

$hero_theme = 'default';
switch ( $this->post->post_type ) {
	case 'post':
		$hero_theme = 'jumbo';
		break;
	case 'page': 
		$hero_theme = 'overlay';
		break;
	default:
		break;
}

// Probably some other stuff, already making this difficult to follow since we're jumping around so much.
$vars = [];
$on = [];
$vars = [];

return [
	/**
	 * Hero component.
	 *
	 * This has 2 themes, jumbo and overlay.
	 */
	( new \WP_Components\Hero() )
		->set_theme( $hero_theme ) // Where did this come from? I've already forgotten it was so long ago since I saw it.
		->get_config( 'theme_name' ),

	// More components.
];

Instead, you can use the callable method to pass a closure which has access to the current component, and can inherit variables from the parent scope with use.

// While inside the return array.
return [
	/**
	 * Hero component.
	 *
	 * This has 2 themes, jumbo and overlay.
	 */
	( new \WP_Components\Hero() )

		/**
		 * Set the theme based on the post type.
		 * 
		 * (see how easy that is to follow?)
		*/
		->callable(
			function( $hero ) : \WP_Components\Hero {
				switch ( $this->post->post_type ) {
					case 'post':
						$hero->set_theme( 'jumbo' );
						break;
					case 'page': 
						$hero->set_theme( 'overlay' );
						break;
					default:
						break;
				}
				return $hero; // Return the component so the chain can continue.
			}
		)
		->get_config( 'theme_name' ), // I know exactly what happened, it's right ^

	// More components.
];
Clone this wiki locally