JS data api method from another plugin

Hello,

This is only a question.

Let’s suppose we want to call a method from another plugin or anything. Is there any option in JS data Api we can use?

For example:
Data-api-url-plugin=“some_plugin”
Data-api-controller=“some_plugin_controller”

This will allow us to reuse some Methods which are present in some plugin ensuring DRY.

This functionality can be achieve via extending but that is also sometimes not desirable.

OR may be this concept is already implemented somewhere.

Hey @ibrarartisan

We don’t often recommend this because a controller should supply all the necessary API endpoints for its view. This is what makes October CMS so nice to use and there are many tools available to make this possible.

However, if you really want to do it, you can use

data-request-url="/url/to/plugin/controller"

This will redirect the request to the plugin’s controller endpoint and all the handlers should be available there. I would consider this approach experimental, so hopefully it works as expected.

1 Like

@daft thanks alot.

Can you explain a bit what you means by

“a controller should supply all the necessary API endpoints for its view”

An example would be great.

It’s a conceptual idea. Say for example, you have a handler called onGetUser and you want it available on two controllers (/preview and /update).

// URL: /preview
class Preview extends Controller
{
    function onGetUser()
    {
        // ...
    }
}

The proposal here is for the /update controller to access the /preview controller using data-request-url

<!-- URL: /update -->
<button data-request="onGetUser" data-request-url="/preview">
    Get User
</button>

This may work, but it is not ideal. Instead, October CMS has concepts called Widgets (Backend) and Components (Frontend), along with Behaviors/Traits that allow you to make the handler definitions portable.

So to make onGetUser available to both controllers, a behavior can be used. For example, UserFunctions can define this handler.

class UserFunctions extends \October\Rain\Extension\ExtensionBase
{
    protected $controller;

    public function __construct($controller)
    {
        $this->controller = $controller;
    }

    public function onGetUser()
    {
        // ...
    }
}

Now each controller can implement it and it becomes available to both without the need to access other URLs.

// URL: /preview
class Preview extends Controller
{
    public $implement = [
        UserFunctions::class,
    ];
}

// URL: /update
class Update extends Controller
{
    public $implement = [
        UserFunctions::class,
    ];
}

See Docs to learn more:

@daft it is perfect. thanks alot.

October cms nevers stops to amaze me. :slight_smile:

1 Like