1. The forums will be archived and moved to a read only mode in about 2 weeks (mid march).

Command Classes

Discussion in 'Development' started by Remarkabless, Dec 16, 2017.

  1. Remarkabless

    Remarkabless Slime

    Messages:
    83
    GitHub:
    Remakem
    hey, I want to know how to seperate my command in a diffrent class, I just want to do it to be more organized because this plugin is of a “big size”. I checked search found multiple threads but noone clearly explained how to seperate a command from main class. Thanks hopefully you guys can help me !
     
  2. Kenn Fatt

    Kenn Fatt Slime

    Messages:
    82
    GitHub:
    kennfatt
    Here is my way:

    1. Create an abstract class that extend Command class and implement PluginIdentifiableCommand class.
    PHP:
    abstract class CommandBase extends Command implements PluginIdentifiableCommand {

       
    /**
        * CommandBase constructor.
        *
        * @param string $name
        * @param string $description
        * @param null $usageMessage
        * @param array $aliases
        */
       
    public function __construct($name$description ""$usageMessage null$aliases = []) {
          
    parent::__construct($name$description$usageMessage$aliases);
       }

       
    /**
        * NOTE: You must implement this function.
        * @return Plugin
        */
       
    public function getPlugin() : Plugin
       
    {
         return 
    Loader::getInstance(); // Loader is my main class.
       
    }
    }
    2. Create separated command classes and extend CommandBase (your abstract class, on point number 1).
    PHP:
    class MyFirstCommand extends CommandBase
    {
       public function 
    __construct()
       {
          
    parent::__construct("firstcommand""My first command!""Usage: /fcmd", ["fcmd"]);
       }

       public function 
    execute(CommandSender $senderstring $commandLabel, array $args)
       {
          
    // a condition that will be executed after player run "/firstcommand" or any aliases.
          // return mixed
       
    }
    }
    3. Don't forget to register your commands to server. Do it in your main class.
    PHP:
    $this->getServer()->getCommandMap()->registerAll("YourPluginNameShouldBeHere", [new MyFirstCommand()]);
    And done! I think its really complicated if you are beginner, there are also many alternatives way and more simple than this one. I used it for big plugin.
     
    Remarkabless likes this.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.