Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Monday 15 August 2016

PHP resize image before base64 encoding

It took me a while to work this out, but it was worth it. base64 encoding can be really useful in presenting and storing images on the web. However you don't want to add a 2000 pixel width base64 encoded image to your database. Here's how to resize the image before it goes in.

<?php
$file = 'mypic.jpg';
$image = imagecreatefromjpeg($file);
$image = imagescale($image , 100);
ob_start();
imagejpeg($image);
$contents = ob_get_contents();
ob_end_clean();
$dataUri = "data:image/jpeg;base64,".base64_encode($contents);
echo '<img src="'.$dataUri.'" />';
?>

Wednesday 23 March 2016

HTML includes like PHP using jQuery

Here I have created a jQuery plugin to perform HTML includes (sub pages)  similar to method possible in PHP.
Find the code here.

Tuesday 22 March 2016

Search multiple database tables using PDO

I have created a PHP class based on PDO. It searches multiple database tables. It handles boolean and normal string queries. Results are displayed as Twitter Bootstrap tables. Find it here.

Wednesday 10 June 2015

Bootstrap formhandler calling class methods with JSON returned and processed

This entry offers a number of techniques through 4 files.

  • index.php contains a message alert which will only be displayed when there is a message to put in it. The forms use an action which contains the name of a class and method which will be used to process the results. There is also a call to custom.js
  • custom.js handles the form submissions and delivers the data returned to the page. It passes the form action and field content to formhandler.php. It receives JSON which then is either passed to a message alert or a data table.
  • formhandler.php receives the call from custom.js. This contains the form action and field content. It takes the form action and uses them to create calls to classes and methods named in the form action. For example and action of myclass/mymethod would be used to create calls similar to those below. The inclusion of the $_POST array allows the form field content to be passed to the class. The data returned is then passed back to custom.js for processing.
$myclass = new myclass($_POST);
$myclass->mymethod;

  • myclassname.class.php contains the example class and methods. The class receives the $_POST array and processes its content. There are 3 methods which demonstrate how to return a string, an array and an object.

This approach is a quick way of utilising many classes. It does not require a .htaccess file to simplify form actions and is flexible in its handling of returned data through JSON.
Have fun.

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Form handler for many PHP classes using jQuery</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
    body
    {
      margin-top:2em;
    }
    #message, #data-table
    {
      display:none;
    }
    </style>
  </head>
  <body>
    <div class="row">
      <div class="container">
        <div class="col-md-12">
          <div id="message" class="alert alert-success" role="alert"></div>
          <!-- <form action="myclassname/myclassmethod_string" method="POST"> -->
          <!-- <form action="myclassname/myclassmethod_array" method="POST"> -->
          <form action="myclassname/myclassmethod_object" method="POST">
            <div class="form-group">
              <label for="name"></label>
              <input type="text" name="name" class="form-control" />
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
          </form>
          <table id="data-table" class="table table-striped">
            <thead>
              <tr>
                <th>Name</th>
                <th>Age</th>
              </tr>
            </thead>
            <tbody>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="custom.js"></script>
  </body>
</html>

custom.js

(function()
{
  $('form').on('submit', function(event)
  {
    $.post('formhandler.php?action='+$(this).attr('action'), $(this).serialize(), function(data)
    {
      var json_obj = JSON.parse(data);
      if(json_obj.hasOwnProperty('message'))
      {
        $('#message').text(json_obj.message);
        $('#message').show();
        $('#message').fadeOut(3000);
      }
      else
      {
        $.each(json_obj, function(name,age)
        {
          $('#data-table > tbody').appendRow(name,age);            
        });
        $('#data-table').show();
      }
    });
    event.preventDefault();
  });
})();

$.fn.appendRow = function()
{
  var s = '<tr>';
  for (var i = 0; i < arguments.length; i++)
  {
    s += '<td>'+arguments[i]+'</td>';
  }
  s += '</tr>';
  return $(this).append(s);
}

formhandler.php

<?php
if(isset($_GET['action']))
{
$arr = split('/', $_GET['action']);
$class = $arr[0];
$method = $arr[1];
require_once $class.'.class.php';
if(class_exists($class))
{
$evalStr = '$'.$class.' = new '.$class.'($_POST);';
eval($evalStr);
if(method_exists($class, $method))
{
$evalStr = '$returnValue = $'.$class.'->'.$method.'();';
eval($evalStr);
}
else
{
$returnValue = 'Method does not exist';
}
}
else
{
$returnValue = 'Class does not exist';
}
}
else
{
$returnValue = 'No action given';
}

if(is_object($returnValue) || is_array($returnValue))
{
echo json_encode($returnValue);
}
else
{
$returnArr = array('message'=>$returnValue);
echo json_encode($returnArr);
}
?>

myclassname.class.php

<?php
class myclassname
{
private $pa;
function __construct($postArray = array())
{
$this->pa = $postArray;
}

function myclassmethod_string()
{
return 'Your name is '.$this->pa['name'];
}

function myclassmethod_array()
{
$myArr = array('Peter'=>'35', 'Ben'=>'37', 'Joe'=>'43');
return $myArr;
}

function myclassmethod_object()
{
$myObj = (object) array('Peter'=>'35', 'Ben'=>'37', 'Joe'=>'43');
return $myObj;
}

function __destruct()
{

}
}
?>

Wednesday 22 April 2015

Display PHP code in the browser

There are 2 ways to do this I've recently discovered:
First, use the highlight_file command thus,
highlight_file('hello.php');

Second, allow .phps files. To do this (I'm using an Ubuntu Apache on local host here), go to the file /etc/apache2/mods-available/php5.conf
Change the line highlighted in red to the one highlighted in blue
<FilesMatch ".+\.phps$">
    SetHandler application/x-httpd-php-source
    # Deny access to raw php sources by default
    # To re-enable it's recommended to enable access to the files
    # only in specific virtual host or directory
    Order Deny,Allow
    Deny from all
    Allow from all
</FilesMatch>
Now, if you rename hello.php to hello.phps and display it in your browser, it will show as PHP code.
Hope this helps.

Thursday 5 February 2015

JS and CSS fall back using PHP

There are several solutions to JS and CSS out there on the web. I've tried quite a few, but I find that if I take my network connection out, they don't work. They don't fall back. Recently, maxcdn.bootstrapcdn.com went down causing websites, including my own, to suffer from a lack of bootstrap. Even though I'd put in some fall back code.
This prompted me to write the following code. Now I know I'll be criticised for using PHP as the solution, but if you've suffered as I have, you may consider this worth a try. Below is the PHP class followed by the HTML page which makes use of the class with the calls highlighted in red. In this case I'm calling Twitter Bootstrap.
callfallback.class.php
<?php
class callfallback
{
function __construct()
{

}

function getCSS($remote, $local)
{
if($this->testExists($remote) == TRUE)
{
echo '<link rel="stylesheet" href="'.$remote.'" />'.PHP_EOL;
}
else
{
echo '<link rel="stylesheet" href="'.$local.'" />'.PHP_EOL;
}
}

function getJS($remote, $local)
{
if($this->testExists($remote) == TRUE)
{
echo '<script src="'.$remote.'"></script>'.PHP_EOL;
}
else
{
echo '<script src="'.$local.'"></script>'.PHP_EOL;
}
}

function testExists($url)
{
$file_headers = @get_headers($url);
if($file_headers[0] == 'HTTP/1.1 200 OK')
{  
 return TRUE;
}
else
{
 return FALSE;
}
}

function __destruct()
{

}
}
?>
index.html
<!DOCTYPE html>
<?php
require_once 'callfallback.class.php';
$cfb = new callfallback;
?>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bootstrap Fallback Template</title>
  <?php
  $cfb->getCSS('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css','css/bootstrap.min.css');
  ?>
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->
  </head>
  <body>
 
  <?php
  $cfb->getJS('https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js','js/jquery-1.11.2.min.js');
  $cfb->getJS('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js','js/bootstrap.min.js');
  ?>
</body>
</html>

Monday 6 October 2014

Using PHP to get YouTube Channel feed into Twitter Bootstrap thumbnails

I've been working on a Twitter Bootstrap site. The client created a YouTube channel and wanted the feed coming into the site. Some of the videos added are uploaded by the users, some come from subscriptions. There is a nice class called thumbnail in Twitter Bootstrap for such things, so I thought I'd use that. I'm happiest getting external data using PHP. Here's how it's done.
Replace the word 'Google' with the name of your channel.
<?php
$url = 'https://gdata.youtube.com/feeds/api/videos?q=Google&max-re%20sults=5&v=2&alt=jsonc&orderby=published';
$json = file_get_contents($url);
$data = json_decode($json);
$items = $data->data->items;
foreach($items as $child)
{
echo '<a href="'.$child->player->default.'" class="thumbnail">';
echo '<h4>'.$child->title.'</h4>';
echo '<img src="'.$child->thumbnail->sqDefault.'" alt="'.$child->title.'" />';
echo '<footer>'.date("jS F Y",strtotime($child->updated)).'</footer>';
echo '</a>';
}
?>

Monday 12 May 2014

Introduction to the PHP5 Command Line Interface (Ubuntu version)

So you'd like to write and run your PHP5 code without using a web browser. Where you run it from the command-line....

First make sure that the php5 cli is installed by typing this on the command line (terminal, shell, whatever you want to call it) :

sudo apt-get install php5-cli

Now it's time to create your first command line script to test. Use your favourite editor to create the following program and save it as hello.php:

<?php
echo 'hello world!';
?>

Now back to the command line. Make sure you are in the same directory as hello.php was saved. Now type:
php5 hello.php

You should see that hello world! is echo'd to the command line.

Now the following program:

  • Takes the first number
  • Assigns it to a variable ($first)
  • Takes the second number
  • Assigns it to a variable ($second)
  • Adds the two numbers together and assigns them to the variable $answer
  • Echo's the value of the variable $answer, then adds a line break.


<?php
echo 'Enter first number ';
$first = fgets(STDIN);
echo 'Enter second number ';
$second = fgets(STDIN);
$answer = $first + $second;
echo 'And the answer is '.$answer.PHP_EOL;
?>

Now you're ready to go.

Wednesday 9 April 2014

Twitter Bootstrap Progress Bar example using jQuery and PHP

So you'd like to see Twitter Bootstrap Progress Bar actually work. Not too many examples out there are there. For this, after you've downloaded Twitter Bootstrap, you will need 3 more files:

  • Your demo file, index.html
  • Your post handler, posthandler.php
  • Your empty data file, datafile.dat which is writeable

So let's start with index.html. Get the basic template from http://getbootstrap.com/getting-started/
and make the following additions (in red). This file:

  • Creates a progress bar
  • Kicks off the post handler using the submit button
  • Checks the value contained in the data file
  • Uses the data gathered to increase the width of the progress bar

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">  
    <style>
    body
    {
      padding-top:2em;
    }  
    </style>
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <div class="row">
      <div class="container">
        <div class="col-md-12">
          <form role="form">
            <button type="submit" class="btn btn-default">Submit</button>
          </form><br />
          <div class="progress progress-striped active">
            <div class="progress-bar" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width:0%">
            </div>
          </div>
        </div>
      </div>
    </div>    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    <script>
    (function()
    {
      $('form').submit(function()
      {
        $.post('posthandler.php', function(data1)
        {
          console.log(data1)
        });

        var refreshId = setInterval(function()
        {
          $.get('datafile.dat', function(data2)
          {
            $('.progress-bar').css('width',data2+'%');
            if(data2 >= 100)
            {
              console.log('finished');
              $('.progress').removeClass('active');
              $('.progress').removeClass('progress-striped');
              $('.progress-bar').text('Complete');
              clearInterval(refreshId);
            }
          });
        }, 100);
        return false;
      });      
    })();
    </script>
  </body>
</html>

Now for the posthandler.php
This script:

  • Clears the data file
  • Every so often, updates the data file contents

<?php
file_put_contents('datafile.dat', '');
for($i = 1; $i <= 100; $i++)
{
usleep(200000);
file_put_contents('datafile.dat', $i);
}
?>

Enjoy!

Wednesday 11 December 2013

Dynamic progress bar for Twitter Bootstrap using PHP

Twitter Bootstrap offers some very useful progress bars. See http://getbootstrap.com/components/#progress
They are based on percentages, so you need to get the length of the shaded bar as a percentage of the whole bar for them to be accurate.

Below is a small example of how to do this with PHP.

<?php
$currentVal = 10;
$maxVal = 20;
$percentageVal = ($currentVal/$maxVal)*100;
?>
<div class="progress">
  <div class="progress-bar" role="progressbar" aria-valuenow="<?php echo $currentVal ?>" aria-valuemin="0" aria-valuemax="<?php echo $maxVal ?>"  style="width:<?php echo $percentageVal ?>%;">
    <span class="sr-only"><?php echo $percentageVal ?> Complete</span>
  </div>
</div>

Recursive delete for blogs and forums

Let's say, you've developed a blog or forum and you need to delete some entries. You will also want to delete the responses to those entries. In this example we'll use a table structure like this, where 'refid' is a field used to associate a response with it's referer :
`id`
`refid`
`userid`
`title`
`content`
`tags`
`created`
In our PHP we want to go through each blog entry which we'd like to delete and ascertain it's responses identified by 'refid' before deleting it. Thus :
function deleterecursiveblog($id)
  {
    $q = "SELECT * FROM `blog` WHERE `refid`='{$id}'";  
    $result = mysqli_query($con,$q);
    if(isset($result))
    {
      foreach($result as $key)
      {
        deleterecursiveblog($key['id']);  
      }
    }
    $q = "DELETE FROM `blog` WHERE `id`='{$id}'";  
    $result = mysqli_query($con,$q);
  }

Thursday 28 November 2013

Error reporting in PHP

I've seen quite a few blogs which go into great depth about error reporting in PHP. What I and almost everyone else wants when something is going wrong is... Tell me everything. So, here are the lines to put at the top of your .php file
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
?>
Job done.

Friday 22 November 2013

OOP Series : Interfaces

An interface is a template of mthods. Not properties. An interface is usually accompanied by an 'implements' clause. Classes which implement an interface must contain the declared methods. There is no defined means of declaring a JavaScript interface/implments combination.
PHP : template.class.php
<?php
interface template
{
function setWidth($width);
function setHeight($height);
}
?>
PHP : document.class.php
<?php
require_once 'template.class.php';
class document implements template
{
public $width, $height;
function setWidth($width)
{
$this->width = $width;
}

function setHeight($height)
{
$this->height = $height;
}
}
?>
Now a file (index.php) which creates a document object.
<?php
require_once 'document.class.php';
$doc = new document;
$doc->setWidth(10);
$doc->setHeight(10);
echo $doc->width.' '.$doc->height;
?>

OOP Series : Abstraction

Abstract classes are particularly useful if you are working in a team and on a large project. They allow the architect to specify what needs to be available in child classes without saying how. They can also be used to specify methods which must be available to all child classes. Abstract classes should't really be called, just referenced. In the example below I have an abstract class of book and a child class of childrensbook. The good news for me in writing the blog post is that there is no abstract class implementation in JavaScript.
PHP : book.class.php
<?php
/* You may only have child classes of this class */
abstract class book
{
function cover()
{
/* All child classes must have this function */
return 'Nice bright cover';
}

/* Must exists in a child class, but you can implement it as you see fit */
abstract function pages();
}
?>
PHP : childrensbook.class.php
<?php
require_once 'book.class.php';
class childrensbook extends book
{
function pages()
{
return 20;
}
}
?>
Now a file (index.php) which creates a childrensbook object.
<?php
require_once 'childrensbook.class.php';
$achildrensbook = new childrensbook;
echo $achildrensbook->cover().'<br />';
echo $achildrensbook->pages().'<br />';
?>

Wednesday 6 November 2013

OOP Series : Encapsulation

One of OOP's strengths is that it provides control over access to properties and methods. This becomes particularly useful when developers are working together and extending classes.It is also often referred to as data hiding. It achieves this through public, private and protected properties and methods. How these are implemented in different languages can vary significantly as you see in the code examples below.
Public usually means anything which makes use of the class can access it.
Private usually means only the class can access it.
Protected usually means either it can access private properties and methods whose values can then be passed back, or can be used only by extended classes.
Given the more complex nature of protected, I tend to use it only when necessary.
PHP : car.class.php
<?php
class car
{
public $mypublicvariable;
private $myprivatevariable;
protected $myprotectedvariable;
function __construct()
{
$this->mypublicvariable = 'guitar';
$this->myprivatevariable = 'beer';
$this->myprotectedvariable = 'chocolate';
}
}
?>
PHP : extendedcar.class.php
<?php
require_once 'car.class.php';
class extendedcar extends car
{
function __construct()
{
parent::__construct();
}

function showprotected()
{
return $this->myprotectedvariable;
}
}
?>
JavaScript : car.class.js
car = function()
{
this.mypublicvariable = 'guitar';
var myprivatevariable = 'beer';

this.myprivilegedmethod = function()
{
return myprivatevariable;
}
}
Now a file (index.php) which creates 2 PHP objects. One from the parent class and one from the extended class. Then 1 JavaScript object.
<?php
require_once 'car.class.php';
require_once 'extendedcar.class.php';
$mycar = new car;
$myextendedcar = new extendedcar;
echo $mycar->mypublicvariable.'<br />';
echo $myextendedcar->showprotected().'<br />';
?>
<script src="car.class.js"></script>
<script>
var mycar = new car();
document.write(mycar.mypublicvariable+'<br />');
document.write(mycar.myprivilegedmethod()+'<br />');
</script>

Friday 1 November 2013

OOP Series : Inheritance

One of OOP's strengths is that it provides the concept of inheritance. This becomes particularly useful when developers are working together and extending classes. In this first example I'm not going to focus on controlling the visibility of properties and methods. Everything will be public. Visibility will be covered in another blog entry.
PHP:car.class.php
<?php
class car
{
public $mypublicvariable;
function __construct()
{
$this->mypublicvariable = 'guitar';
}
function changevalue()
{
$this->mypublicvariable = 'beer';
}
}
?>
PHP:extendedcar.class.php
<?php
require_once 'car.class.php';
class extendedcar extends car
{
function __construct()
{
parent::__construct();
}
function changevalue()
{
$this->mypublicvariable = 'chocolate';
}
}
?>
JavaScript:car.class.js
car = function()
{
this.mypublicvariable = 'guitar';
}
car.prototype.changevalue = function()
{
this.mypublicvariable = 'beer';
}
JavaScript:extendedcar.class.js
extendedcar = function()
{
car.call(this);
}
extendedcar.prototype = new car();
extendedcar.prototype.constructor = car;
extendedcar.prototype.changevalue = function()
{
this.mypublicvariable = 'chocolate';
}
Now a file (index.php) which creates an object from both.
<?php
require_once 'car.class.php';
require_once 'extendedcar.class.php';
$mycar = new car;
$myextendedcar = new extendedcar;
echo $mycar->mypublicvariable.'<br />';
$mycar->changevalue();
echo $mycar->mypublicvariable.'<br />';
echo $myextendedcar->mypublicvariable.'<br />';
$myextendedcar->changevalue();
echo $myextendedcar->mypublicvariable.'<br />';
?>
<script src="car.class.js"></script>
<script src="extendedcar.class.js"></script>
<script>
var mycar = new car();
var myextendedcar = new extendedcar();
document.write(mycar.mypublicvariable+'<br />');
mycar.changevalue();
document.write(mycar.mypublicvariable+'<br />');
document.write(myextendedcar.mypublicvariable+'<br />');
myextendedcar.changevalue();
document.write(myextendedcar.mypublicvariable+'<br />');
</script>

Friday 25 October 2013

OOP Series : Constructors and destructors

In OOP, constructors are initialisers and destructors are clean up operations.
In the case of PHP you declare a constructor of your class. It will be run when an object is created from the class. You can also declare a destructor which will be "called as soon as there are no other references to a particular object, or in any order during the shutdown sequence."
In the case of JavaScript, you don't have a specific method, but just make all your declarations.
In JavaScript, it's best to rely upn the garbage collector.
PHP:familyphoto.class.php
<?php
class familyphoto
{
public $mywidth, $myheight;
function __construct($mywidth = NULL, $myheight = NULL)
{
$this->mywidth = $mywidth;
$this->myheight = $myheight;
}

function __destruct()
{
$this->mywidth = NULL;
$this->myheight = NULL;
}
}
?>
JavaScript:familyphoto.class.js
familyphoto = function(mywidth, myheight)
{
this.mywidth = typeof mywidth !== 'undefined' ? mywidth : null;
this.myheight = typeof myheight !== 'undefined' ? myheight : null;
}
Now a file (index.php) which creates 2 objects from both. In one, passing no values, and in another, passing 2 required values.
<?php
require_once 'familyphoto.class.php';
$familyphoto1 = new familyphoto;
echo $familyphoto1->mywidth.'<br />';
echo $familyphoto1->myheight.'<br />';
$familyphoto2 = new familyphoto(4,3);
echo $familyphoto2->mywidth.'<br />';
echo $familyphoto2->myheight.'<br />';

?>
<script src="familyphoto.class.js"></script>
<script>
var familyphoto1 = new familyphoto();
document.write(familyphoto1.mywidth+'<br />');
document.write(familyphoto1.myheight+'<br />');
var familyphoto2 = new familyphoto(4,3);
document.write(familyphoto2.mywidth+'<br />');
document.write(familyphoto2.myheight+'<br />');
familyphoto1.destruct();
familyphoto2.destruct();
</script>

Monday 21 October 2013

OOP Series : Properties and methods

Why? I don't know, but the creators of OOP decided to rename variables and functions as properties and methods respectively. The crazy thing is, that in the code, you will see references to things like 'var' and 'function'. Hey ho! Here are 2 simple examples of how they are declared and used in my example of the desk lamp which lights up my keyboard on this dull day.
PHP : desklamp.class.php
<?php
class desklamp
{
public $power = 'OFF';
function onoffswitch()
{
$this->power = $this->power == 'OFF' ? 'ON' : 'OFF';
}
}
?>
JavaScript : desklamp.class.js
desklamp = function()
{
this.power = 'OFF';

this.onoffswitch = function()
{
this.power = this.power == 'OFF' ? 'ON' : 'OFF';
};
};
Now a file (index.php) which creates objects from both and makes the switch.
<?php
require_once 'desklamp.class.php';
$mydesklamp = new desklamp;
echo 'PHP desk lamp power = '.$mydesklamp->power.'<br />';
$mydesklamp->onoffswitch();
echo 'PHP desk lamp power = '.$mydesklamp->power.'<br />';
?>

<script src="desklamp.class.js"></script>
<script>
var mydesklamp = new desklamp;
document.write('JS desk lamp power = '+mydesklamp.power+'<br />');
mydesklamp.onoffswitch();
document.write('JS desk lamp power = '+mydesklamp.power);
</script>

Wednesday 16 October 2013

A short series on OOP (Object Orient(at)ed Programming)

I'm going to do a short series of blog entries on OOP. I'll be using 2 languages in order to emphasise that the concepts are not language specific. All then entries will have simple code to demonstrate the point and be short in text.

Why OOP?

Good question Mick. Funnily enough, when you begin learning a language, it's rare to dive into OOP. It's possible that just grapsing this first concept would be enough to put any newbie off. Unfortunately, this also presents it's own problem. The newbie was doing perfectly well, creating useful code, only to be held up by a new concept (OOP) which slows them down. So the first question on their mind is why do I have to learn OOP? What is it going to give me.

Enough Mick. Give me the answer. Here I probably attack the problem from a different point of view than many of my programming friends.

Suppose I asked you to explain something. The mug of tea I'm drinking from. You might say, It's a cylindrical object, just big enough to hold, with a handle. It's yellow. They don't always look like that. Some are small for espresso, some are blue etc.

This would be an OOP way of looking at a mug of tea. Something which actually comes naturally to us. Strangely, if you were to use the concept we come into programming with (procedural), you'd describe the cup of tea as, 'It is the thing I am drinking from'.

First concept - classes and objects

So, here is the first concept. What is a class, and what is an object?
A class is a description of the thing. An object is a version of the thing.
Using our cup of tea example, we create a class called 'cup of tea', and in order to have a cup of tea, we need to create an object (my cup of tea).

Time to start coding I think. We are going to do this with 2 languages; PHP and JavaScript. First the classes.
PHP : cupoftea.class.php
<?php
class cupoftea
{
public $height, $diameter, $colour;
}
?>

JavaScript : cupoftea.class.js
cupoftea = function()
{
var height, diameter, colour;
};

Now a file (index.php) which creates objects from both.
<?php
require_once 'cupoftea.class.php';
$mycupoftea = new cupoftea;
$mycupoftea->height = 20;
echo $mycupoftea->height;
?>

<script src="cupoftea.class.js"></script>
<script>
var mycupoftea = new cupoftea;
mycupoftea.height = 30;
document.write(mycupoftea.height);
</script>

Thursday 1 August 2013

HTML5 contenteditable save, re-save and save again

The HTML5 contenteditable attribute is really useful, but when you've got my typing skills, you'd really like to keep saving as you go. In the example below I'm writing to a text file for simplicity. I've got a few things going on.

  • If the text file exists or has data in there, I use it. Otherwise, the editable paragraph holds a default string.
  • I use a form submit to kick off a jQuery event.
  • The jQuery function calls a PHP script to write the contents of my editable paragraph to the file.

This way I can keep pressing the submit button as I go, which will just update the text file with the current editable paragraph contents.

Here's the code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Editable jQuery save</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
</script>
</head>
<body>
<p id="content" contenteditable="true">
<?php
$text = file_get_contents('test.txt');
if(!empty($text))
{
echo $text;
}
else
{
echo 'Put some text here.';
}
?>
</p>
<form>
<input type="submit" />
</form>
<script>
(function()
{
$('form').submit(function()
    {
        $.post('set.php',
        {
            content:$('#content').text()
        }, function(data)
        {
        if(data)
        {
        console.log(data)
        }    
        });
        return false;
    });
})();
</script>
</body>
</html>

And set.php

<?php
if(isset($_POST['content']))
{
file_put_contents('test.txt', $_POST['content']);
}
else
{
echo 'write was not successful';
}
?>