Skip to content

Services

Brov3r edited this page Jul 15, 2024 · 1 revision

Services

Avrix implements a system of communication between plugins - Services It is very similar to the system from MC Bukkit

The whole point is to create an interface in the main plugin and implement it. All other plugins that add the first one as a library will be able to access this implementation through this interface using ServiceManager

For example, let's write a simple interface in the main plugin:

/**
 * Example of an interface for services
 */
public interface Example {
    int getInt();
    void sayHello(String Text);
}

Now its implementation:

/**
 * An example of implementing a service using an interface
 */
public class ExampleImpl implements Example{
    @Override
    public int getInt() {
        return 111;
    }

    @Override
    public void sayHello(String text) {
        Logger.print("Hello " + text);
    }
}

Great, all that remains is to register it:

/**
 * Main entry point of the example plugin
 */
public class Main extends Plugin {
    /**
     * Constructs a new {@link Plugin} with the specified metadata.
     * Metadata is transferred when the plugin is loaded into the game context.
     *
     * @param metadata The {@link Metadata} associated with this plugin.
     */
    public Main(Metadata metadata) {
        super(metadata);
    }

    /**
     * Called when the plugin is initialized.
     * <p>
     * Implementing classes should override this method to provide the initialization logic.
     */
    @Override
    public void onInitialize() {
        ServiceManager.register(Example.class, new ExampleImpl());
    }
}

After these steps, our implementation is registered in the database and all other plugins will be able to access it. Important! In all “child” plugins, the main one must be specified in the dependencies as compileOnly, otherwise there will be a conflict of plugin resources. In addition, the dependency must also be clearly stated in metadata.yml in the corresponding line indicating the version of the main plugin.

An example of a child plugin calling the main one:

/**
 * Main entry point of the example plugin
 */
public class AnotherPlugin extends Plugin {
    /**
     * Constructs a new {@link Plugin} with the specified metadata.
     * Metadata is transferred when the plugin is loaded into the game context.
     *
     * @param metadata The {@link Metadata} associated with this plugin.
     */
    public Main(Metadata metadata) {
        super(metadata);
    }

    /**
     * Called when the plugin is initialized.
     * <p>
     * Implementing classes should override this method to provide the initialization logic.
     */
    @Override
    public void onInitialize() {
        Example example = ServiceManager.getService(ExampleImpl.class);
        int testInt = example.getInt();
    }
}
Clone this wiki locally