How access to own class method in Twig

Hello. I want to write my own class method in PHP (I think I must create plugin by devtools at the beginning. That will be class where I’ll add my method). In this method I want to get some data. Next I want to have access to this method in all templates(as instantiated object from this class) and set Twig variable to returned data from my method.

I cannot find example in Grav how to do it. So can you explain me step by step.

@pawel, A rough example might give you an idea to start from.

I presume you have already found the plugin tutorial where you can learn the basic structure of a plugin.

There are many events you can subscribe to and one of them is onTwigSiteVariables. This is where you should add any variables to Twig that need to be available to Twig during this process.

The following is a sketch of /user/plugins/myplugin/myplugin.php:

class MyPlugin extends Plugin
{
    public static function getSubscribedEvents()
    {
        return [
            'onPluginsInitialized' => ['onPluginsInitialized', 0]
        ];
    }

    public function onPluginsInitialized()
    {
        if ($this->isAdmin()) {
            $this->active = false;
            return;
        }

        $this->enable([
            'onTwigSiteVariables' => ['onTwigSiteVariables', 0],
        ]);
    }

    /**
     * Add variables to Twig.
     */
    public function onTwigSiteVariables()
    {
        $twig = $this->grav['twig'];
        $twig->twig_vars['myClass'] = new MyClass();
        $twig->twig_vars['myVariable'] = $myVariable;
    }
}

In Twig, you can now call methods and properties of the instance of MyClass or access provided variables.

{% set returnValue = myClass.myMethod() %}
{% set property = myClass.myProperty %}
{% set variable = myVariable %}

Hope this gives you an idea to start from…

Thanks for the explaination. I understood how I must process. I have made two plugins needed for me.