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

Services

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

A service is meant to be a unique feature of your plugin. But is not a component but will use components to do what it needs. A service is also a group of things to accomplish the feature, meaning a service folder might have a few classes, Javascript, and CSS.

Creating a Service

Just make a folder in services/ like services/my-service and add a class-my-service.php (see autoloading) that looks like:

<?php

namespace YourCompanyName\YourPluginName;

class My_Service {

    public function hooks() {
    }

    public function run() {
    }
}

Now go find class-app.php and find attach_services method and add e.g. the following:

$this->my_service = new Example_Service();

This will attach the service to your app() and you can access it with app()->my_service from other services loaded this same way. All your services can talk to each other this way and it's not wrong to build dependencies between your services this way but it is suggested to keep dependencies to a minimum.

Note that your service's class file will be autoloaded and will now have it's run, hooks, and deactivate_plugin methods run automatically if the contain these methods.

Clone this wiki locally