Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.
Aubrey Portwood edited this page Feb 3, 2019 · 10 revisions

What is App or app()?

The App class or app() function are loaded as a shell around your services and components. It loads services and components automagically and allows you to talk to different parts of your plugin using the app() function.

It also supplies a slew of useful tools that are commonly used throughout most plugins. It's created automatically in the base plugin file, you can see what it does there.

app() usage example

Let's say you have two services:

<?php

namespace CompanyNamespace\ProjectNamespace;

class Service_One {
	public function get_content() {
		return app()->service_two->the_text();
	}
}
<?php

namespace CompanyNamespace\ProjectNamespace;

class Service_Two {
	public function hooks() {
		add_filter( 'the_content', [ $this, 'replace' ] );
	}

	public function replace( $content ) {
		return app()->service_one->get_content();
	}

	public function the_text() {
		return 'The content';
	}
}

And you attach them in attach_services method of app/class-app.php like so:

$service_one = new Service_One();
$service_two = new Service_Two();

As you can see in Service_Two it is actually calling something from Service_One via:

app()->service_two->get_content();

and it's calling Service_Two via:

app()->service_one->the_text();

As long as the class is public, you can do this. This helps out a lot when another service has maybe done it's job and the second service wants to get data from the first one and vice versa.

Components shouldn't use app()

Components, as a rule, should not use app() to talk to other services, thought you can. This is because now your component will have a dependency on a Service that will have to move around with it, which is undesired when you want to use a component in a totally different feature. The developer using your component would have to remove that dependency manually.

We may add something to the app() call that will fail when you call app() from a component.

Clone this wiki locally