Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 13 Next »

Description

This example shows us how to PHP with SmartClient framework.

SmartClient applications are single page applications most of the time. All the javascript and HTML is loaded or generated dynamically, and most of the time users don't need to leave the initially loaded page. 

Prerequisites

  • In order to connect the database, You need to download the RedBean ORM Library. The RedBean PHP ORM library can be download here.

How to use the RedBeanPHP?

  • To install 

     After unzipping the RedBeanPHP, you will see just the rb.php.

    This file contains everything you need to start RedBeanPHP. Just include it in your PHP script like this:

     

        require 'rb.php';

     

    You are now ready to use RedBeanPHP!

  • To setup

    So, you have decided to start with RedBeanPHP. The first thing you need to get started is setting up the database. Luckily this is really easy.

     require('rb.php');
        R::setup('mysql:host=localhost;
            dbname=mydatabase','user','password');
  • Queries

     

    R::getAll( 'select * from supplyitem' );

    Note:

    RedBeanPHP only works with the InnoDB driver for MySQL. MyISAM is toolimited.

 

How to build the project with PHP?

This example shows how to use the PHP with SmartClient ListGrid component, by connection RedBean ORM library with a ListGrid. The following steps are required:

Create server-side code to fetch data from database and respresent it in the JSON format necessary for SmartClient components:

    1. This code will perform the fetching and return the response in JSON format, Please create the fetch.php. 

      fetch.php
      <?php 
          // importing the RedBean library
      	require 'rb.php';
      	// Including the DSResponse source
          require 'DSResponse.php';
      	
          // Connecting to the database	
      	R::setup('mysql:host=[HOSTNAME];dbname=[DB_NAME],'USER_NAME','PASSWORD');			
      	// Get the data source list
      	$products = R::getAll('Select * from supplyitem');
      	// Disconnect to the database
      	R::close();
       
          // SmartClient accept JSON in special format, 
      	$response = new DSResponse();	
      	$response->setData($products);
      	$response->setStartRow(0);
      	$response->setEndRow(count($products)-1);
      	$response->setTotalRows(count($products));
      	$response->setStatus(0);
      	// Convert from DSResponse Object to Array for JSON encoding
      	$result['response'] = (Array)$response;	
      	// Create JSON from php data structure and output it.	 
      	echo json_encode($result); 
      ?>
    2. bean.php

      DResponse.php
      <?
      	abstract class Bean { 
      		public function __get($propertyName) {
      			$method = 'get' . ucfirst($propertyName);
      			if (!method_exists($this, $method)) {
      				$method = 'is' . ucfirst($propertyName);
      				if(!method_exists($this, $method)) {
      					throw new Exception('Invalid read property ' . $propertyName . ' in ' . get_class($this) . ' class.');
      				}
      			}
      			return $this->$method;
      		}
      
      		public function __isset($propertyName) {
      			try {
      				$_value = $this->__get($propertyName);
      				return !empty($_value);
      			} catch (Exception $e) {
      				/* if a property isn't readable it isn't set*/
      				return false;
      			}
      		}
      
      		public function __set($propertyName, $value) {
      			$method = 'set' . ucfirst($propertyName);
      			if ('mapper' == $method || !method_exists($this, $method)) {
      				throw new Exception('Invalid write property ' . $propertyName . ' in ' . get_class($this) . ' class.');
      			}
      			return $this->$method($value);
      		}
      
      		public function populate(array $map = null) {
      			if(!empty($map)) {
      				foreach($map as $key => $value) {
      					try {
      						$this->__set($key, $value);
      					} catch (Exception $e) {
      						/* evaluated $key isn't a bean writable property. Let's go to next one */
      					}
      				}
      			}
      
      			return $this;
      		}
      	}
      
      
      
      

       

      c. DSResponse.php

      DResponse.php
      <?php 	 
      	require 'bean.php';
      
      	class DSResponse extends Bean
      	{
      		// variables
      		/* Read/Write property*/
      		var $data;		
      		/* Read/Write property*/
      		var $startRow;
      		/* Read/Write property*/
      		var $endRow;
      		/* Read/Write property*/
      		var $totalRows;
      		/* Read/Write property*/
      		var $status;
      
      		public function setData($value) {			 
      			$this->data = empty($value) ? null : (Array)$value;
      			return $this;
      		}
      		public function getData( )
      		{
      			return $this->data;
      		}
      
      		public function setStartRow($value) {			
      			$this->startRow = (int)$value;
      			return $this;
      		}
      		public function getStartRow(  )
      		{
      			return $this->startRow;
      		}
      
      		public function setEndRow($value) {			
      			$this->endRow = (int)$value;
      			return $this;
      		}
      		public function getEndRow(  )
      		{
      			return $this->endRow;
      		}
      
      		public function setTotalRows($value) {			
      			$this->totalRows = (int)$value;
      			return $this;
      		}
      		public function getTotalRows(  )
      		{
      			return $this->totalRows;
      		}
      
      		public function setStatus($value) {			
      			$this->status = (int)$value;
      			return $this;
      		}
      		public function getStatus(  )
      		{
      			return $this->status;
      		}
      
      	}

 

Creating the database

Create a database on mysql server management tool like phpmyadmin, workbrench etc.

Once the mysql service started, please run the following sql:

database.sql
create database app1;

And please create the new table:

Column nameData TypeAllow NullsAdditional
iteamIDintNoidentity and Primary Key
itemNamevarchar(128)No 
SKUvarchar(10)No 
descriptionvarchar(2000)Yes 
categoryvarchar(128)Yes 
unitsvarchar(5)No 
unitCostfloatYes 
inStockintYes 
nextShipmentdatetimeYes 

Save the table with the name "supplyItem",  then open the table data and add one two of sample rows(so that the ListGrid we ultimately load this data into has some valid rows to display).

 

Creating the DataSource and the controller to handle the requests

Create the index.php and change it's content to:

index.html
<HTML>
<HEAD>
	<SCRIPT>var isomorphicDir = "Scripts/isomorphic/";</SCRIPT>
    <SCRIPT SRC="Scripts/isomorphic/system/modules/ISC_Core.js"></SCRIPT>
    <SCRIPT SRC="Scripts/isomorphic/system/modules/ISC_Foundation.js"></SCRIPT>
    <SCRIPT SRC="Scripts/isomorphic/system/modules/ISC_Containers.js"></SCRIPT>
    <SCRIPT SRC="Scripts/isomorphic/system/modules/ISC_Grids.js"></SCRIPT>
    <SCRIPT SRC="Scripts/isomorphic/system/modules/ISC_Forms.js"></SCRIPT>
    <SCRIPT SRC="Scripts/isomorphic/system/modules/ISC_DataBinding.js"></SCRIPT>
    <SCRIPT SRC="Scripts/isomorphic/skins/TreeFrog/load_skin.js"></SCRIPT>
</HEAD><BODY>
<SCRIPT>
isc.RestDataSource.create({
    ID:"suppyItem",
    fields:[
        {name:"itemID", type:"sequence", hidden:"true", primaryKey:"true"},
        {name:"itemName", type:"text", title:"Item", length:"128", required:"true"},
        {name:"SKU", type:"text", title:"SKU", length:"10", required:"true"},
        {name:"description", type:"text", title:"Description", length:"2000"},
        {name:"category", type:"text", title:"Category", length:"128", required:"true"},
        {name:"units", type:"enum", title:"Units", length:"5",
            valueMap:["Roll", "Ea", "Pkt", "Set", "Tube", "Pad", "Ream", "Tin", "Bag", "Ctn", "Box"]
        },
        {name:"unitCost", type:"float", title:"Unit Cost", required:"true",
            validators:[
                {type:"floatRange", min:"0", errorMessage:"Please enter a valid (positive) cost"},
                {type:"floatPrecision", precision:"2", errorMessage:"The maximum allowed precision is 2"}
            ]
        },
 
        {name:"inStock", type:"boolean", title:"In Stock"},
        {name:"nextShipment", type:"date", title:"Next Shipment"}
    ],
 
    dataFormat:"json",
    dataURL:"/fetch.php"
 
});
isc.ListGrid.create({
    ID: "suppyItem",
    width: 700, height: 224, alternateRecordStyles: true,
    dataSource: suppyItem,
    autoFetchData: true
});
</SCRIPT>
</BODY></HTML> 

 

Open the web browser and call the url, the application will start and  a grid fetching and displaying the rows found in the table will be shown.

Date fields are correctly displayed, and if null, are missing from the grid.

The complete code for this sample project can be downloaded from here.

Note: Afeter you download the php code, please don't forget to copy the SmartClient archive to the scripts directory.

  • No labels