Showing posts with label oop. Show all posts
Showing posts with label oop. Show all posts

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>

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>

Friday 11 October 2013

Start building your OOP JavaScript objects

Let's face it. Sometimes jQuery doesn't cut it. Either you don't want the user to download the library or it seems to be a sledgehammer to crack a nut. JavaScript has also matured into a great server-side language. Think of node.js. My example below uses OOP JavaScript for web interaction, but consider the concept on the server-side too.
Let's start with the HTML page:
<html>
<script src="alertster.class.js"></script>
<script>
var myalertster = new alertster('hello');
myalertster.sendit('goodbye');
</script>
</html>
Not too big is it? Essentially we are creating a new object called myalertster from a class called alertster which lies within a file called alertster.class.js. I am passing a couple of parameters here, but as you'll see from the contents of alertster.class.js (below), I've stuck a little error trapping in there too.
Now for alertster.class.js:
function alertster(message)
{
message = typeof message !== 'undefined' ? message : 'Default message';
this.m = message;
this.sendit = function(additional)
{
additional = typeof additional !== 'undefined' ? additional : 'Default additional message';
alert(this.m+"\n"+additional);
};
};
Easy!

Tuesday 7 August 2012

OOP PHP Authentication Class

This class relies upon the existence of a databases class, such as the one listed here, to go away and check of the username and password match. If they do, a session and cookie is created.


<?php
require_once 'database.class.php';

class authenticate
{
public $id;
private $username;
private $password;
private $db;

function __construct()
{
$this->db = new database;
}

function login($u, $p)
{
$this->username = mysql_real_escape_string($u);
$this->password = mysql_real_escape_string(md5($p));
$q = "SELECT * FROM users WHERE username='{$this->username}' AND password='{$this->password}'";
$result = $this->db->query($q);
if($result)
{

    $this->id = $result->id;
    $this->username = $result->username;

$this->createSessionAndCookies();
}
else
{
$this->destroySessionAndCookies();
}
}

function logout()
{
$this->destroySessionAndCookies();
}

private function createSessionAndCookies()
{
@session_start();
$_SESSION['AUTH_ID'] = $this->id;
$_SESSION['AUTH_USERNAME'] = $this->username;
$expire=time()+3600*24*30;
setcookie('AUTH_ID', $this->id, $expire);
setcookie('AUTH_USERNAME', $this->username, $expire);
echo 'session and cookie created';
}

private function destroySessionAndCookies()
{
unset($_SESSION['AUTH_ID']);
unset($_SESSION['AUTH_USERNAME']);
session_destroy();
setcookie('AUTH_ID', '', time()-3600);
setcookie('AUTH_USERNAME', '', time()-3600);
echo 'session and cookie destroyed';
}

function __destruct()
{

}
}
?>

Monday 6 August 2012

OOP PHP Vimeo Class

This is essentially the earlier mentioned RSS class with a couple of tweaks for vimeo and search.

First, a script to call the class:

<?php
require_once 'vimeo.class.php';

$addr1 = 'http://vimeo.com/api/v2/channel/videoschool/videos.xml';
$addr2 = 'http://vimeo.com/api/v2/channel/wineaftercoffee/videos.xml';

$vimeo = new vimeo;
$vimeo->addFeed($addr1);
$vimeo->addFeed($addr2);

$arr = $vimeo->getFeed();

/* Or
$arr = $vimeo->getFeed('water');
*/

/*
Or
$searchArray = Array('glass', 'trix');
$arr = $vimeo->getFeed($searchArray);
*/

foreach($arr as $row)
{
echo '<iframe src="http://player.vimeo.com/video/'.$row->id.'" width="WIDTH" height="HEIGHT" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe><br />';
}
?>


Now, the class itself:


<?php
class vimeo
{
public $addr = NULL;
private $outArr = Array();
function __construct($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
if($this->addr)
{
return $this->addFeed();
}
}

function addFeed($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
$rss = simplexml_load_file($this->addr);
$this->outArr = array_merge($this->outArr, $rss->xpath('/videos//video'));
}

function getFeed($input = NULL)
{
usort($this->outArr, function ($x, $y)
{
if (strtotime($x->pubDate) == strtotime($y->pubDate)) return 0;
    return (strtotime($x->pubDate) > strtotime($y->pubDate)) ? -1 : 1;
});

if(is_array($input))
{
$this->outArr = $this->getArrayFilteredFeed($input);
}
elseif(is_string($input))
{
$this->outArr = $this->getStringFilteredFeed($input);
}

return $this->outArr;
}

private function getStringFilteredFeed($s)
{
$tempArr = Array();
foreach($this->outArr as $row)
{
if(stristr($row->title,$s) || stristr($row->description,$s))
{
array_push($tempArr, $row);
}
}
return $tempArr;
}

private function getArrayFilteredFeed($arr)
{
$tempArr = Array();
foreach($this->outArr as $row)
{
foreach ($arr as $key) 
{
if(stristr($row->title,$key) || stristr($row->description,$key))
{
array_push($tempArr, $row);
}
}
}
return $tempArr;
}
}
?>

Thursday 19 July 2012

Simple PDO Class

For some reason, maybe it was my first (negative) introduction to OOP through C++, I've always hated those (::) double colons. So, when I started to look at PHP Data Objects (PDO), although it seemed like  a good idea, I couldn't get over the fact that I was opening myself up to using static class and methods with all the syntax which goes with it.

So I started to create a simple database class which made use of PDO, which would be a little friendlier to call. Humble beginnings these. First I created an ini file for all the settings, which looks something like this:

DB_TYPE = mysql
DB_HOST = localhost
DB_USERNAME = jimmy
DB_PASSWORD = password
DB_NAME = testdb

Then, I created the database class which called the ini file thus:

<?php
class database
{
private $config;
private $connection;
private $pdoString;
  function __construct()
{
$this->config = (object) parse_ini_file('config.ini', true);
$this->pdoString = $this->config->DB_TYPE;
$this->pdoString .= ':dbname='.$this->config->DB_NAME;
$this->pdoString .= ';host='.$this->config->DB_HOST;
$this->connection = new PDO($this->pdoString, $this->config->DB_USERNAME, $this->config->DB_PASSWORD);
}


public function query($q)
{
    return $this->connection->query($q);
}


function __destruct()
{
$this->connection = NULL;
}
}
?>
Finally, I created a calling page to see how it ran:

<?php
require_once 'database.class.php';
$db = new database;
$arr = $db->query('SELECT * FROM users');
foreach($arr as $row)
{
echo $row['username'].'<br />';
}
?>
It's a start.


Friday 13 July 2012

OOP PHP RSS Reader

This is a simple RSS Reader which allows you to add multiple feeds. It also sorts the results before returning them to the calling page.
The calling page would look something like this:


<?php
require_once 'rss.class.php';
$addr1 = 'http://feeds.bbci.co.uk/sport/0/football/rss.xml';
$addr2 = 'http://feeds.howtogeek.com/HowToGeek';
$addr3 = 'http://feeds.feedburner.com/TheEdTechie';
$rss = new rss;
$rss->addFeed($addr1);
$rss->addFeed($addr2);
$rss->addFeed($addr3);
$arr = $rss->getFeed();
foreach($arr as $row)
{
echo $row->title.'-'.$row->pubDate.'<br />';
}
?>

So, here's the RSS Reader class:


<?php
class rss
{
public $addr = NULL;
private $outArr = Array();
function __construct($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
if($this->addr)
{
return $this->addFeed();
}
}


function addFeed($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
$rss = simplexml_load_file($this->addr);
$this->outArr = array_merge($this->outArr, $rss->xpath('/rss//item'));    
}


function getFeed()
{
usort($this->outArr, function ($x, $y)
{
if (strtotime($x->pubDate) == strtotime($y->pubDate)) return 0;
    return (strtotime($x->pubDate) > strtotime($y->pubDate)) ? -1 : 1;
});
return $this->outArr;
}
}
new rss;
?>

Thursday 28 June 2012

OOP PHP POST handler in 2 parts

Actually, I'm wrong before I've even started. The class I give you below will also handle GET requests too. I've described it in 2 parts. The first is some HTML and jQuery which can be used to test the class. Then there is the class itself.

The HTML delivers a form with an input field and submit button. It also contains a jQuery call to the POST handler. Here, I pass the method within the class which will be called to handle the data. Then I pass the data. In this case, the contents of the input field. Finally, An alert catches any data coming back from the class.

The POST handler accepts the POST request as and converts it into an object. It checks to see if a method has been called and that the method exists. If so, the method is invoked. If not, an error message is returned.

Enjoy!

The HTML


<!DOCTYPE html>
<html lang="en">
<head>
<title>Post test</title>
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
</head>
<body>
<form>
<label for="myname">Type your name</label>
<input type="text" name="myname" id="myname" />
<button type="submit">Submit</button>
</form>
<script>
(function()
{
$('form').submit(function()
{
$.post('posthandler.php',
{
method:'getContent',
myname:$(this).find('#myname').val()
}, function(data)
{
alert(data)
});
return false;
});
})();
</script>
</body>
</html>

The Class


<?php
class posthandler
{
private $postObject;
function __construct($p)
{
$this->postObject = (object) $p;
if($this->postObject->method && (method_exists($this, $this->postObject->method)))
{
$evalStr = '$this->'.$this->postObject->method.'();';
eval($evalStr);
}
else
{
echo 'Invalid method supplied';
}


}
function getcontent()
{
echo $this->postObject->myname;
}
}
new posthandler($_POST);
?>

Monday 5 March 2012

Multiple inheritance through PHP using traits

I actually took this code from http://php.net. Multiple inheritance has always been a bit dodgy for me in PHP. This is an excellent example of how to use traits to achieve it.

<?php
trait Hello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait World {
    public function sayWorld() {
        echo ' World';
    }
}

class MyHelloWorld {
    use Hello, World;
    public function sayExclamationMark() {
        echo '!';
    }
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();>
?>