Create Service

Overview #

You may see this pattern in KoolReport

class MyReport extends \koolreport\KoolReport
{
    use \koolreport\clients\Bootstrap;
    use \koolreport\export\Exportable;
}

The Bootstrap and Exportable are examples of services added to KoolReport. There are two areas that services will solve. First is to extend functionality of KoolReport, adding new methods like export() in Exportable service. Second is to intercept event and change behaviors like Bootstrap does. Bootstrap service intercept the OnBeforeEvent to add bootstrap CSS to your report.

The service uses a feature of PHP called trait to add new methods to a class.

Add new method to KoolReport #

You create MyService.php with following content

<?php

trait MyService
{
    public function doThing()
    {
        echo "do thing";
    }
}

Now you can use your service inside your report

class MyReport extends \koolreport\KoolReport
{
    use MyService;
}

you will have the method doThing() available:

$report = new MyReport;
$report->doThing();

Intercept event and change behaviors #

In your service trait, you create a method following this template:

trait MyService
{
    public function __contructMyService()
    {
        ...
    }
}

Now when your service is added to a report, the __constructMyService() method will be invoked on report's initiation.

In the __constructMyService() method, you can register events and handle the events.

For example:

trait EchoRunEnd
{
    public function __contructEchoRunEnd()
    {
        $this->registerEvent("OnRunEnd",function(){
            echo "Report has been run";
        });
    }
}

So if your reporrt use the EchoRunEnd, every time you run your report with $report->run() method, you will see the text "Report has been run" echoed on your browser.

Summary #

In this section, we have learned how to create new service for KoolReport. The service is used to extend functionality for your report or to change behaviors of your report. If you have any questions regarding this, please let us know.

Get started with KoolReport

KoolReport will help you to construct good php data report by gathering your data from multiple sources, transforming them into valuable insights, and finally visualizing them in stunning charts and graphs.