Skip to content

Create a new Vote Method

This section explains how to extend Condorcet by creating your own voting method.

You can implement a new voting method by following the interface and structure expected by the Condorcet engine. This allows you to integrate custom algorithms and use them as you would with built-in methods.

Take inspiration from the simplified example below. Read code from CondorcetPHP\Condorcet\Algo\Method (abstract class) and CondorcetPHP\Condorcet\Algo\MethodInterface (interface). You should also read CondorcetPHP\Condorcet\Algo\Methods\Copeland code, it's a simple and efficient implementation.

Basic example

php
<?php
namespace AnotherNamespace {
    use CondorcetPHP\Condorcet\Algo\Method;
    use CondorcetPHP\Condorcet\Algo\MethodInterface;
    use CondorcetPHP\Condorcet\Algo\Stats\BaseMethodStats;
    use CondorcetPHP\Condorcet\Algo\Stats\StatsInterface;
    use CondorcetPHP\Condorcet\Result;

    class NewVotingMethod extends Method implements MethodInterface
    {
        public const array METHOD_NAME = ['FirstMethodName','Alias1','Alias_2','Alias 3'];

        protected ?Result $result = null;


        // Get the Result object
        public function getResult () : Result
        {
            // Cache
            if ( $this->result !== null )
            {
                return $this->result;
            }

                //////

            // Ranking calculation
            $thePairwise = $this->getElection()->getPairwise();

            $result = [0=> [3], 1=> [0,4], 2 => [2]]; // Candidate must be valid internal candidate key.

            $this->result = $this->createResult($result);

            // Return
            return $this->result;
        }


        // Compute the Stats
        protected function getStats () : StatsInterface
        {
            return new BaseMethodStats([]);
        }

    }
}

You must register this algorithm this way: <<< @/code_snippets/register_new_vote_method.php

Released under the MIT License.