KoolReport PHP Reporting Framework

repository·master·Indexed 42 days ago

https://github.com/koolphp/koolreport

An open-source PHP reporting framework for fast and flexible data processing and visualization. It features a node-based pipeline for connecting to various data sources (MySQL, MongoDB, CSV, Excel, etc.), applying transformations via processes like Group, Sort, and Limit, and rendering reports using interactive widgets. Requires PHP 5.4 or higher.

Tokens
11.7K
Snippets
42
Records
49
Agent score
53%

What's inside KoolReport

  1. What is included in KoolReport core

    master

    The core package structure includes:

    • packages/: Extended packages
    • src/: Core logic divided into:
      • clients/: Clients for various services
      • core/: The main framework engine
      • datasources/: Connectors for MySQL, SQL Server, Oracle, MongoDB, CSV, Excel, etc.
      • processes/: Data transformation tools (join, group, filter, etc.)
      • widgets/: Visualization components (charts, tables)
    • autoload.php: The main entry point for loading the framework.
  2. Install KoolReport via Composer

    master

    To install the latest version of KoolReport, use Composer.

    Note: This repository is being transitioned. For the latest version, it is recommended to use the new repository koolreport/core via:

    composer require koolreport/core

    For this specific repository, use:

    composer require koolphp/koolreport
  3. How to create a basic KoolReport

    master

    A standard KoolReport implementation consists of three main parts: a bootstrap file (index.php), a report definition class (SalesByCustomer.php), and a view file (SalesByCustomer.view.php).

    1. The Bootstrap File (index.php)

    This file initializes the report class, runs the data processing, and renders the view.

    <?php
    require_once "SalesByCustomer.php";
    
    $salesByCustomer = new SalesByCustomer;
    $salesByCustomer->run()->render();

    2. The Report Class (SalesByCustomer.php)

    Extend \koolreport\KoolReport to define your data sources and processing pipeline.

    • settings(): Define your dataSources. Each source requires a class (e.g., \koolreport\datasources\CSVDataSource) and configuration parameters (e.g., filePath).
    • setup(): Define the data pipeline. Use $this->src('source_name') to select a source, then use ->pipe() to pass data through various processes (like Group, Sort, or Limit) before saving it to a dataStore using ->pipe($this->dataStore('store_name')).

    3. The View File (SalesByCustomer.view.php)

    Use widget classes to render the processed data. Widgets typically use ::create() and require a dataStore name that matches the one defined in the setup() method.

    <?php 
        use \koolreport\widgets\koolphp\Table;
        use \koolreport\widgets\google\BarChart;
    ?>
    
    <?php
    BarChart::create(array(
        "dataStore" => $this->dataStore('sales_by_customer'),
        "columns" => array(
            "customerName" => array("label" => "Customer"),
            "dollar_sales" => array("type" => "number", "label" => "Amount")
        )
    ));
    ?>
    <?php
    require_once "../koolreport/autoload.php";
    
    use \koolreport\processes\Group;
    use \koolreport\processes\Sort;
    use \koolreport\processes\Limit;
    
    class SalesByCustomer extends \koolreport\KoolReport
    {
        protected function settings()
        {
            return array(
                "dataSources"=>array(
                    "sales"=>array(
                        "class"=>'\koolreport\datasources\CSVDataSource',
                        "filePath"=>"orders.csv",
                    ),
                )
            );
        }
    
        protected function setup()
        {
            $this->src('sales')
            ->pipe(new Group(array(
                "by"=>"customerName",
                "sum"=>"dollar_sales"
            )))
            ->pipe(new Sort(array(
                "dollar_sales"=>"desc"
            )))
            ->pipe(new Limit(array(10)))
            ->pipe($this->dataStore('sales_by_customer'));
        }
    }
  4. How the reporting pipeline works with Nodes

    master

    KoolReport uses a 'legos-like' structure where the reporting pipeline is composed of Node objects. Data flows from source nodes through various processing nodes to destination nodes.

    Key concepts of the Node model:

    • Piping: You connect nodes using the pipe() method. This establishes a relationship where the current node sends data to the next node in the chain.
    • Streaming: Data is processed as a stream of rows (associative arrays). Nodes receive data via input(), process it, and pass it forward using next().
    • Lifecycle: A node's lifecycle involves receiving a startInput() signal, processing data via onInput(), and eventually receiving an endInput() signal once all upstream sources have finished.
    • Metadata: Nodes can pass metaData through the pipeline using receiveMeta() and sendMeta(), allowing non-row information to travel alongside the data stream.
    // Example of connecting nodes in a pipeline
    $source->pipe($processor)->pipe($destination);
  5. Understand the Widget base class

    master

    The koolreport\core\Widget class is the foundation for all visual components in KoolReport, such as charts and tables. A widget is responsible for managing its own data, resources (JS/CSS), and rendering its visual representation via templates.

    When creating a custom widget, you typically extend this class and override onInit() for setup, onRender() for defining the view, and resourceSettings() to declare required assets.

  6. Use DataStore for data manipulation

    master

    The DataStore class is a core component used to hold, iterate, and manipulate collections of data. It behaves like an array but provides powerful methods for filtering, sorting, joining, and aggregating data. It implements IteratorAggregate and ArrayAccess, allowing it to be used in foreach loops and accessed via array syntax.

    // Basic instantiation with data
    $rows = [
        ['id' => 1, 'name' => 'Alice', 'age' => 30],
        ['id' => 2, 'name' => 'Bob', 'age' => 25],
    ];
    $dataStore = new \koolreport\core\DataStore($rows);
    
    // Iterating through the DataStore
    foreach ($dataStore as $row) {
        echo $row['name'] . PHP_EOL;
    }
  7. Create a custom theme by extending the Theme class

    master

    To implement a custom visual style for KoolReport, you must create a class that extends koolreport\core\Theme. You will need to override several protected methods to define your theme's identity, supported widgets, and color schemes.

    Key methods to implement:

    • themeInfo(): Returns an associative array containing name, version, base (e.g., 'bs4'), and cssClass (the class to be attached to widgets).
    • themeWidgets(): Returns an associative array of supported widgets and their associated resource paths (JS/CSS).
    • allColorSchemes(): Returns an associative array of color schemes, where each scheme is an array of hex color strings.
    • onInit(): An optional lifecycle method called during construction.
    namespace myapp\theme;
    
    use koolreport\core\Theme;
    
    class MyCustomTheme extends Theme
    {
        protected function onInit()
        {
            // Initialization logic
        }
    
        public function themeInfo()
        {
            return [
                "name" => "My Custom Theme",
                "version" => "1.0.0",
                "base" => "bs4",
                "cssClass" => "my-custom-theme-class",
            ];
        }
    
        protected function allColorSchemes()
        {
            return [
                "default" => ["#000", "#333", "#666", "#999", "#bbb", "#ddd", "#fff"],
                "ocean" => ["#0077be", "#00a3e0", "#5f9ea0", "#add8e6"],
            ];
        }
    
        protected function themeWidgets()
        {
            return [
                'koolreport\widgets\chart\Chart' => [
                    'folder' => 'assets/chart',
                    'js' => ['chart.js'],
                    'css' => ['chart.css'],
                ],
            ];
        }
    }
  8. Initialize a widget with parameters

    master

    Widgets are initialized with a $params array. Key parameters you can pass include:

    • name: The unique name of the widget.
    • report: The report instance containing this widget.
    • dataSource or dataStore: The data to be used by the widget.
    • onReady: A JavaScript string to be executed on the client-side once the widget is ready.
    • themeBase: The theme base (e.g., bs3, bs4).
    • themeCssClass: Custom CSS classes to attach to the widget.
    • withoutLoader: Boolean; if true, the widget will not render with the KoolReport Loader.
    $params = [
        "name" => "my_chart",
        "dataSource" => $dataStore,
        "onReady" => "function(name) { console.log(name + ' is ready'); }",
        "themeBase" => "bs4"
    ];
    $widget = new MyCustomWidget($params);
  9. Extend the DataSource class to create custom data sources

    master

    The koolreport\core\DataSource class is the foundation for all data sources in KoolReport. When building a custom data source, you should extend this class and override the onInit() method to handle connection setup or data fetching logic.

    Data flows from the DataSource through a series of processes until it reaches a datastore. You trigger this flow by calling start(), or by allowing the framework to call requestDataSending() when a downstream node in the data chain requests data.

    <?php
    namespace myapp;
    
    use koolreport\core\DataSource;
    
    class MyCustomDataSource extends DataSource
    {
        protected function onInit()
        {
            // Custom logic to set up connection or prepare data
        }
    
        public function start()
        {
            // Logic to pull data from the source and pipe it to the next node
        }
    }
  10. How to group multiple processes using ProcessGroup

    master

    A ProcessGroup is a specialized Process used to encapsulate a sequence of data processing steps into a single unit. To use it, you must extend the ProcessGroup class and implement the setup() method to define the data flow using the incoming() and outcoming() methods.

    In the setup() method, you typically pipe the incoming() node (the entry point of the group) through one or more Process instances and finally pipe the last process into the outcoming() node (the exit point of the group).

    This abstraction allows you to treat a complex pipeline of multiple transformations as if it were a single process in a larger report pipeline.

    class MyGroup extends ProcessGroup
    {
        public function setup()
        {
            $this->incoming()
                ->pipe(new ProcessA())
                ->pipe(new ProcessB())
                ->pipe($this->outcoming());
        }
    }
  11. Install Oracle driver for Apache on Windows

    master

    To use OracleDataSource on a Windows environment with Apache, follow these steps:

    1. Install Oracle Database (32-bit): Since PHP on Windows is typically 32-bit, you must install the 32-bit version of the Oracle database.
    2. Configure Oracle Instant Client:
      • Download and extract the Oracle Instant Client 32-bit.
      • Add the extracted folder to your Windows Path environment variable.
    3. Install Visual Studio Redistributable: Install the version required by your Instant Client (e.g., VC 2013 for Instant Client 12.2.0.1.0).
    4. Configure Apache:
      • Copy all .dll files from the Oracle Instant Client 32-bit folder into Apache's bin folder.
      • Enable the extension in php.ini (e.g., extension=php_oci8_12c.dll).
      • Restart Apache.

    For PDO with Oracle on Windows:

    • Follow the same steps as above, but instead of the OCI8 extension, enable extension=php_pdo_oci.dll in php.ini and restart Apache.