Defining Functions


Introduction

Plugin functions are called like {% verbatim %}{{ example_function('some-params') }}{% endverbatim %} in views. This article will show you how to define them and return usable information.

Defining Functions

Override the getFunctions method within your plugin class to get started:

<?php namespace Test\FooPlugin;

use Anomaly\Streams\Platform\Addon\Plugin\Plugin;

class FooPlugin extends Plugin
{

    /**
     * Returns a list of functions.
     *
     * @return array An array of functions
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('hello', function($name) {
                return "Hello {$name}!";
            })
        ];
    }
}

Building a Function

To build a function simply create an instance of the Twig_SimpleFunction class and return it. The above example provides add a hello function to use in views:

{% verbatim %}{{ hello('Ryan') }} // Hello Ryan!{% endverbatim %}

Leveraging Commands

It is highly recommended to bundle your function logic into a command so you can defer injection of dependencies and keep your code tidy:

new \Twig_SimpleFunction('example', function(array $data) {
    return $this->dispatch(new DoSomethingCool($data);
})

Decorating Data

If you are returning a presentable object like a collection of entry you will first want to decorate it using the \Anomaly\Streams\Platform\Support\Decorator class:

new \Twig_SimpleFunction('example', function($param) {
    return (new Decorator)->decorate($this->dispatch(new FindAllWidgets($param));
})

Wildcard Functions

If you have a class that you want to expose to the view layer entirely you can use wildcard functions instead of defining each method as a function individually:

new \Twig_SimpleFunction('utility_*', function($name) {

    $arguments = array_slice(func_get_args(), 1);

    return call_user_func_array([app(Utility::class), camel_case($name)], $arguments);
})