Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Components

Aubrey Portwood edited this page Feb 3, 2019 · 19 revisions

What is a component?

A component is not a feature of your project but is a tool that your feature(s) uses. In fact it may be a tool that many features on many plugins use over and over such as our cli component which I've personally used in many projects where we build a CLI command.

Note that the cli component is used by the replace-cli service as are many of the other components.

Creating a component

All components start off with a folder in the components/ directory, e.g. my-component/. You then create a class-my-component.php (see autoloading) file that has a class in it like:

<?php

namespace MyCompanyNameSpace\My_Component;

class My_Component {
	public function get_value() {
		return 'My Value';
	}
}

Now that component is available anywhere you create a new \MyCompanyNameSpace\My_Component\My_Component() and components/class-my-component.php is autoloaded automatically.

Note, since your component has it's own folder, it can have it's own Javascript, CSS, libraries, and even other classes.

Using a component

The below service attaches a component to itself for use.

<?php

namespace YourCompanyName\YourPluginName;

class My_Service {

    // Not it's public for the example below for access.
    public $my_component;

    public function __construct() {

        // Note that the full namespace is used since components are not namespaced with your project (intentionally) for mobility.
        $this->my_component = new \MyCompanyNameSpace\My_Component\My_Component();
    }

    public function hooks() {
        ...
    }

    public function run() {
        $value = $this->my_component->get_value();
    }
}

Accessing a component from another service using app():

<?php

namespace YourCompanyName\YourPluginName;

class My_Other_Service {

    public function __construct() {
        ...
    }

    public function hooks() {
        ...
    }

    public function run() {
        $value = app()->my_service->my_component->get_value();
    }
}
Clone this wiki locally