Categories: Tutorials

Creating Charts with Zend Framework 3 and FusionCharts using Database

In this tutorial, we will be creating JavaScript charts using Zend and FusionCharts using database connectivity. Here we will explain everything from installation to the database connectivity, rendering and displaying of the chart in the web browser. Before you move on with this tutorial make sure that you have completed the Part 1(building a static chart using Zend and FusionCharts) of this tutorial series.

Overview

  1. Introduction to Zend Framework
  2. Introduction to Fusioncharts
  3. Installing Zend Framework 3 and Setting up the your Project
  4. Setting up the virtual host
  5. Installing Fusioncharts
  6. Creating a chart with database using Fusioncharts

Prerequisites

Before you move forward with the tutorial you should have a basic understanding of how things work in Zend Framework. Click here to get detailed description about the Zend Framework 3.

Introduction to Zend Framework

Zend Framework is a cluster of professional PHP packages that can be used to develop web applications and services using PHP 5.6+. It provides 100% object oriented code using a broad spectrum of language features.

Introduction to Fusioncharts

FusionCharts is a comprehensive JavaScript charting library packed with simple and complex charts (like the column and bar charts, pie and doughnut charts, treemap, heatmap, logarithmic charts), gauges and widgets (like the angular gauge, bulb gauge, thermometer gauge, and funnel and pyramid charts), and maps (for all continents, major countries, and all US states).. Let’s now get started with the steps for creating a chart with static data using Zend Framework and FusionCharts.

Step 1: Installing Zend Framework 3 and setting up the project

In order to build our application, we will start with the ZendSkeletonApplication available on github. Use Composer to create a new project from scratch, as shown below:
$ composer create-project -s dev zendframework/skeleton-application path/to/install
This will install an initial set of dependencies, which includes:
  • zend-component-installer, which helps automate the injection of component configuration into your application
  • zend-mvc, which is the kernel for MVC applications
It will ask you a couple of questions which will be regarding the support provided by Zend. You can do y(yes) to all the questions or you may acquire them later by simple command:
$ composer require "name of the dependency you want"
First, it will prompt:
$ Do you want a minimal install (no optional packages)? Y/n
If you answer with a “Y”, or press enter with no selection, the installer will not raise any additional prompts and finish installing your application. If you answer “n”, it will continue (for about ten questions) to prompt you with questions. Now you can see that there is a skeleton-application folder created in the path you have specified in the above command. Now you can change the folder name to anything you want , in our case we have renamed the directory skeleton-application to zend_fusioncharts. Once done, go inside the directory that you have set above (In our case the zend_fusioncharts ) and run the following command to install all the dependencies:
$composer self-update
$composer install
Now the project is completely set. If you’ve followed all the steps correctly, you should see the following output if you traverse to the public folder of your project (localhost/zend_fusioncharts/public/):

Step 2: Setting up the virtual host

For this project, we are using the Apache Web Server. You can download the Apache web server from here. Here’s how you can set up the virtual-host for your project:

For Windows users:

  1. Open C:\WINDOWS\system32\drivers\etc\hosts in Notepad or a script editor. Look for the following line at the bottom:
    127.0.0.1   localhost
  2. On a separate line, enter 127.0.0.1, followed by tab space and the name of the virtual host you want to register. For instance, to set up a virtual host called zend_local, enter the following:
    127.0.0.1   zend_local
  3. Open httpd.conf, the main Apache configuration file, in a text editor. It is in the Apache conf folder. If you’re using XAMPP, the file is located at C:\xampp\apache\conf\httpd.conf. Scroll down to the Supplemental configuration section at the end, and locate the following section (approximately line no. 500):
    #Virtual hosts
    #Include conf/extra/httpd-vhosts.conf
  4. Remove the # from the beginning of the second line so the section now looks like this:
    #Virtual hosts
    Include conf/extra/httpd-vhosts.conf
  5. Save httpd.conf and close it.
  6. Open the extra\httpd-vhosts.conf file in Notepad or a text editor. If you’re using XAMPP, the location is C:\xampp\apache\conf\extra\httpd-vhosts.conf.
  7. Add a new virtual host in the vhost.conf.
        ServerAdmin webmaster@dummy.com
        DocumentRoot "C:/xampp/htdocs/zend_fusioncharts/public"
        ServerName zend_local
        ErrorLog "logs/dummy-host2.example.com-error.log"
        CustomLog "logs/dummy-host2.example.com-access.log" common
    
  8. The main section looks like this:
  9. Save the changes made in step 7 httpd-vhosts.conf, and restart Apache.
  10. Now you can load your project by writing https://zend_local/ in the browser.

For Linux (LAMP)

  1. Open your terminal and go to /etc/apache2/sites-available/
    $ cd /etc/apache2/sites-available/
  2. Copy the default config (000-default.conf)
    $ sudo cp 000-default.conf zend_local.conf
  3. Open the new config file that you have created in step 3 and edit it to add the following code:
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html/skeleton/public
        ServerName zend_local
        SetEnv APPLICATION_ENV "development"
    
        
         DirectoryIndex index.php
         AllowOverride All
         Require all granted
     
    
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    
    After you’ve saved all the changes , it should look something like the image given below:
  4. Run the following command
    $ sudo a2ensite example.com.conf
  5. Now open the hosts file in /etc/ and add the hostname for the website
    $ 127.0.0.1 zend_local
  6. Save all the changes and restart the apache server using the command given below:
    $ sudo service apache2 restart

Step 3: Installing Fusioncharts

You can download the latest version of FusionCharts Suite XT from here. Alternately, you can also install it using the npm or bower package managers, using the commands given below: For npm :
npm install fusioncharts
npm install fusionmaps
For Bower:
bower install fusioncharts
bower install fusionmaps
Once you have successfully downloaded the FusionCharts Suite XT execute the steps given below to add the FusionCharts library to your project:
  1. Now create a folder named fusioncharts in the public folder of your project.
  2. Copy all the files from the js folder of the Fusioncharts XT Suite to the fusioncharts folder in the public directory of your project
  3. Download the FusionCharts PHP wrapper to create charts in PHP. You can download it from here.
  4. After the download is complete and you have extracted all the files copy the fusioncharts.php file.
  5. Create a folder Lib in the vendor directory of your project and paste the fusioncharts.php file in the Lib folder.
  6. Open a file called layout.phtml (layout.phtml is a default template provided by Zend) in modules / Application / view / layout / and add the following lines of code after the other script tags:
    headscript()
    ->prependFile($this->basePath(‘fusioncharts/fusioncharts.js’))
    ?>
This completes the installation of FusionCharts.

Step 4: Setting up the Database

Open the file global.php and in the zend_fusioncharts/config/ and add these lines of code:
 [
     'driver' => 'Pdo',
     'dsn'    => 'mysql:dbname=FC;host=localhost',
 ],
 'service_manager' => [
     'factories' => [
      'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
     ],
 ],
];?>
Create a new file called local.php in zend_fusioncharts/config/ and add the following code to it:
 [
      'username' => 'Your username for mysql connection',
      'password' => 'Your password for mysql connection',
     ],
    ];
?>
Now create a table and insert the following data in the Mysql database.
CREATE TABLE albums (id INTEGER PRIMARY KEY AUTO_INCREMENT, month varchar(100) NOT NULL, revenue varchar(100) NOT NULL);
INSERT INTO album (month, revenue) VALUES ('Jan', '4500');
INSERT INTO album (month, revenue) VALUES ('Feb', '4600');
INSERT INTO album (month, revenue) VALUES ('Mar', '4800');
INSERT INTO album (month, revenue) VALUES ('Apr', '4500');
INSERT INTO album (month, revenue) VALUES ('May', '4700');
INSERT INTO album (month, revenue) VALUES ('June', '3500');
INSERT INTO album (month, revenue) VALUES ('July', '4500');
INSERT INTO album (month, revenue) VALUES ('Aug', '4100');
INSERT INTO album (month, revenue) VALUES ('Sep', '4200');
INSERT INTO album (month, revenue) VALUES ('Oct', '4500');
INSERT INTO album (month, revenue) VALUES ('Nov', '4000');
INSERT INTO album (month, revenue) VALUES ('Dec', '5500');

Step 5: Creating a chart using Fusioncharts

Setting up the Fusioncharts module

Start by creating a directory called Fusioncharts under module with the following sub-directories to hold the module’s files: Let’s create Module.php file now, with the following contents:
 [
       Model\FusionchartsTable::class => function($container){
        $tableGateway = $container->get(Model\FusionchartsTableGateway::class);
        return new Model\FusionchartsTable($tableGateway);
       },
       Model\FusionchartsTableGateway::class => function($container){
        $dbAdapter = $container->get(AdapterInterface::class);
        $resultSetPrototype = new ResultSet();
        $resultSetPrototype->setArrayObjectPrototype(new Model\Fusioncharts());
         return new TableGateway('Albums', $dbAdapter, null, $resultSetPrototype);
       }
      ],
     ];
 }

 public function getControllerConfig()
 {
     return [
         'factories' => [
             Controller\FusionchartsController::class => function($container) {
                 return new Controller\FusionchartsController(
                     $container->get(Model\FusionchartsTable::class)
                 );
             },
         ],
     ];
 }
}
?>

Autoloading

Open composer.json in your project root, and look for the autoload section; it should look like the following by default:
"autoload": {
    "psr-4": {
        "Application\\": "module/Application/src/"
    }
},
We’ll now add our new module to the list, so it now reads:
"autoload": {
    "psr-4": {
        "Application\\": "module/Application/src/",
        "Fusioncharts\\": "module/Fusioncharts/src/"
    }
},
Once you’ve made that change, run the following to ensure Composer updates its autoloading rules:
$ composer dump-autoload

Configuration

Create a file called module.config.php under zend_fusioncharts/module/Fusioncharts/config/:
namespace Fusioncharts;

use Zend\ServiceManager\Factory\InvokableFactory;

return [
    'controllers' => [
        'factories' => [
            Controller\FusionchartsController::class => InvokableFactory::class,
        ],
    ],
    'view_manager' => [
        'template_path_stack' => [
            'album' => __DIR__ . '/../view',
        ],
    ],
];

Informing the application about our new module

We now need to tell the ModuleManager that this new module exists. This is done in the application’s config/modules.config.php file which is provided by the skeleton application.
return [
    'Zend\Form',
    'Zend\Db',
    'Zend\Router',
    'Zend\Validator',
    'Application',
    'Fusioncharts',
];
Note: `Fusioncharts` has been added to the above code

Routing and controllers

The mapping of a URL to a particular action is done using routes that are defined in the module’s module.config.php file. So now update the file module.config.php in the config folder of your module.
>namespace Fusioncharts;

use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;

return [
    'controllers' => [
        'factories' => [
            Controller\FusionchartsController::class => InvokableFactory::class,
        ],
    ],

    // The following section is new and should be added to your file:
    'router' => [
        'routes' => [
            'fusioncharts' => [
                'type'    => Segment::class,
                'options' => [
                    'route' => '/fusioncharts[/:action[/:id]]',
                    'constraints' => [
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'     => '[0-9]+',
                    ],
                    'defaults' => [
                        'controller' => Controller\FusionchartsController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
        ],
    ],

    'view_manager' => [
        'template_path_stack' => [
            'fusioncharts' => __DIR__ . '/../view',
        ],
    ],
];

Creating the controller

We are now ready to set up our controller. For zend-mvc, the controller is a class that is generally called {Controller name}Controller; note that the controller’s name must start with a capital letter. The controller class lives in a file called {Controller name}Controller.php within the Controller subdirectory for the module; in our case it is module/Fusioncharts/src/Controller/. Each action is a public method within the controller class that is named as {action name}Action, where {action name} should start with a lowercase letter. Next, to use Fusioncharts in that Controller you need to include the fusioncharts.php wrapper in this file. Let’s go ahead and create our controller class in the file zend_fusioncharts/module/Fusioncharts/src/Controller/FusionchartsController.php:
table = $table;
 }
   
 //Used to the index action which will render index.phtml that has a chart with static data
 // link -> __ServerName__/fusioncharts/index or __ServerName__/fusioncharts/index
 public function indexAction()
 {
   
 }
    
 //Used to the index action which will render index.phtml that has a chart with data returned from the database
 //link -> __ServerName__/fusioncharts/db/
 public function dbAction()
 {   
     return new ViewModel([
         'albums' => $this->table->fetchAll(),
     ]);
 }   
}    
?>

Setting up the Model

Let’s start by creating a file called Fusioncharts.php under the directory module/Fusioncharts/src/Model and populate it with the code given below:
namespace Fusioncharts\Model;

class Fusioncharts
{
    public $id;
    public $artist;
    public $title;

    public function exchangeArray(array $data)
    {
        $this->id     = !empty($data['id']) ? $data['id'] : null;
        $this->artist = !empty($data['artist']) ? $data['artist'] : null;
        $this->title  = !empty($data['title']) ? $data['title'] : null;
    }
}
Next, create a file called FusionchartsTable.php under the module/Fusioncharts/src/Model directory and populate it with the code given below:
namespace Fusioncharts\Model;

use RuntimeException;
use Zend\Db\TableGateway\TableGatewayInterface;

class FusionchartsTable
{
    private $tableGateway;
    public function __construct(TableGatewayInterface $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }
    public function fetchAll()
    {
        return $this->tableGateway->select();
    }
}

Initialise the view scripts

To integrate the view into our application, we need to create some view script files. These files will be executed by the DefaultViewStrategy and will be passed any variables or view models that are returned from the controller action method. So now create a file called db.phtml in modules/Fusioncharts/view/fusioncharts/fusioncharts/db.phtml And add the following code:
 $album->month , "value" => $album->revenue];
     array_push($datas, $data) ;
 }

 //Call the Fusioncharts Class to render the chart
 $columnChart = new FusionCharts("column2d", "myFirstChart1" , 600, 300, "chart 2", "json",
     '{
         "chart": {
             "caption": "Quarterly Revenue",
             "subCaption": "Last year",
             "xAxisName": "Quarter",
             "yAxisName": "Amount (In USD)",
             "theme": "fint",
             "numberPrefix": "$",
             //Setting the usage of plot gradient
             "usePlotGradientColor": "1",
             //Custom plot gradient color
             "plotGradientColor": "#eeeeee"
         },
         "data": '.json_encode($datas).'
     }'
 );
 //Rendering Chart
 $columnChart->render();       
?>

Fusion Charts will render here
After this is done you are good to go this url https://zend_local/fusioncharts/db you’ll get :

Conclusion

This was the complete step-by-step process for creating a chart using the Zend Framework with FusionCharts, using database. If you have completed the tutorial and want to recall the same steps of creating charts using static data, you can move on to the first part, which talks about creating charts using Zend and Fusioncharts with static data.
Dishank Tiwari

View Comments

  • Hola, estoy siguiendo tu tutorial y me esta dando un error me gustaría poder enviártelo a ver si me puedes ayudar.

  • Hi.
    I am working in a Zend Framework project and I need to create a graph with two lines, taking data using a sql query from a database.
    My error is in the final part of the code, I hope you can help me.
    Thank you.

Recent Posts

Pie Charts: A Slice of Data You Can’t Ignore

Ever had a data set that seemed more complicated than a Rubik's cube? You’re not…

3 weeks ago

Venn Diagrams: A Simple Yet Powerful Tool for Visualizing Relationships

We’ve all seen them in textbooks or presentations—those overlapping circles that simplify complex information into…

4 weeks ago

Announcing FusionCharts v4.1: Elevate Your Data Visualization Experience!

We’re excited to announce the upcoming release of FusionCharts v4.1—a groundbreaking step forward in the…

1 month ago

Bubble Maps: Visualizing Data Like Never Before

Have you ever been overwhelmed by a massive data set and wondered, "How do I…

1 month ago

Stock Charts: Mastering the Art of Visualizing Financial Data

If you’ve ever tried to make sense of the stock market, you’ve probably come across…

2 months ago

What is a Bar Chart Used For?

Imagine you’re comparing the sales performance of your top product lines across different regions, or…

3 months ago