harryg harryg - 9 months ago 54
PHP Question

Using HighchartsPHP library in CakePHP

I am trying to use ghunti's HighchartsPHP wrapper in CakePHP so I can use it in my project.

In the demo it says to edit the

and include the script and you then have access to the
class to build charts. This would work for a flat php project but in MVC it works a bit differently I guess.

The first step is how to include the library in my app. I have placed the files in a directory in the
folder called
and in my controller file I have placed the code

App::import('HighchartsPHP', 'Highchart');

When I attempt to instatiate a new
object I am met with

Error: Class 'Highchart' not found

Question 1: what's the correct way to include this library in my project?

Assuming the above is solved, I presume I would build the actual chart from its data in the controller and then pass the chart object to the view for rendering? So in one of my page actions in the controller I might put

$chart = new Highchart();
$chart->series[0]->name = 'Tokyo';
$chart->series[0]->data = array(7.0, 6.9, 9.5);

And then

$this->set( compact( 'chart' ) );

to pass to the view where I would render the chart with:

<?php echo $chart->render("chart"); ?>

Question 2: Is this correct and if not how should I do this?


Your controller should be like this:

App::import('Vendor', 'HighchartsPHP/Highchart');

class ChartsController extends AppController {

    public function index() {        

        $chart = new Highchart();

        $chart->chart = array(
            'renderTo' => 'container', // div ID
            'type' => 'line'

        $chart->series[0]->name = 'Tokyo';
        $chart->series[0]->data = array(7.0, 6.9, 9.5);

        $this->set( compact( 'chart' ) );


and index.ctp:

<?php $chart->printScripts(); ?>

<script type="text/javascript">
    <?php echo $chart->render("chart");?>