SnapShooter Backups Server, Database, Application and Laravel Backups - Get fully protected with SnapShooter

Jpgraph with CakePHP

JpGraph is an Object-Oriented Graph creating library for PHP >= 5.1 The library is completely written in PHP and ready to be used in any PHP scripts. In this tutorial, we will go through the basic steps on how to setup Jpgraph in CakePHP, and the final goal is to implement the very first example of Jpgraph in CakePHP.

Preparation

  • Download CakePHP, in this tutorial we are using CakePHP 1.3.2.
  • Download Jpgraph for PHP 5 from http://jpgraph.net/download
  • Setup CakePHP, make sure it can connect to your database and tmp folder writable. If you don't have the knowledge of setting up CakePHP, please refer to its official site at Cookbook.

Setup vendor files

  • Create a "jpgraph" folder inside directotry "app/vendors/", and copy your downloaded all jpgraph files from "jpgraph-3.0.7\src" to "app/vendors/jpgraph". So now you have a vendors file directory similar to below:

Setup controller

  • Create controller class at "app/controllers/jpgraphs_controller.php", because we don't need a model for this tutorial, we will set it to null.
<?php
class JpgraphsController extends AppController {
	public  $name = 'Jpgraphs';	
	public  $uses = null;
	 
	 public function index(){
	 	$this->layout='default';
	 }
 }
?>

Setup layout file

  • Create default layout file at "app/views/layouts/default.ctp", we output the content of the view directly:
<?php echo $content_for_layout; ?>

Setup view

Create testing view page at "app/views/jpgraphs/index.ctp", take a close look at the code, in CakePHP we are using "App::import('Vendor', 'jpgraph/XXXX')" to include Jpgraph classes, whereas we are using "require_once()" statement when using it regularly. This is the only difference between regular use and using it in CakePHP.

<?php 
App::import('Vendor', 'jpgraph/jpgraph');
App::import('Vendor', 'jpgraph/jpgraph_line');

$ydata = array(11,11,11);

// Create the graph. 
$graph = new Graph(350,250);	
$graph->SetScale("textlin");
$graph->img->SetMargin(30,90,40,50);
$graph->xaxis->SetFont(FF_FONT1,FS_BOLD);
$graph->title->Set("Example 1.1 same y-values");

// Create the linear plot
$lineplot=new LinePlot($ydata);
$lineplot->SetLegend("Test 1");
$lineplot->SetColor("blue");
$lineplot->SetWeight(5);

// Add the plot to the graph
$graph->Add($lineplot);

// Display the graph
$graph->Stroke();



?> 

// ]]>

The end

Now open your browser and type in "http://your-domain//jpgraphs", you should be able to see a chart created by Jpgraph as below: img If you like our tutorial, please follow us on Twitter and help spread the word. We need your support to continue.