Object Oriented Programming Basic: PHP

Video tutorial illustrates basics of OOP in PHP.

Things covered:
Defining class.
Creating Objects.
Public and Private access of Properties/Data.
Separating Class file and the application file.

What is a Class ?
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.

Class Add
add.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
< ?php
class Add
{
private $a;
private $b;
 
function setValues($v1, $v2)
{
   $this->a = $v1;
   $this->b = $v2;
}
 
function add()
{
return( $this->a + $this->b );
}
}
?>

class is a keyword. Add is the name of the class we’ve assigned.
$a and $b are two variables of class Add. These have private access specifier, meaning, they’re not accessible directly from outside the class.
Public access specifier indicates that they can be accessed even outside the scope of a class. Private variables are treated as safe, so we prefer that.

Since private variables are accessed inside the class, we declared two methods inside the class Add. i.e., setValues() and add()
setValues() has two parameters which are then assigned to the local variables $a and $b using the $this pointer.

$this pointer references to the object which is currently pointing to it.

add() method adds the user passed values and returns the result.

Application File
index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
?php
 include_once('add.php');
 
$add = new Add();
 
$add->setValues(50, 100);
echo $add->add();
 
$add->setValues(150, 100);
echo '<br />'.$add->add();
 
$add2 = new Add();
 
$add2->setValues(500, 1000);
echo '<br />'.$add2->add();
 
?>

Here we include the add.php file and create an object of (class)type Add.
Using this object we pass values to setValues(), and then call add() method, which returns the added value of the passed numbers. which is then output to the browser.

We could create as many objects as we wish and then pass and output as many results as required, without altering the class file what so ever, once finalized.

So this is the power of Object Oriented Programming.
This way we could manage complex applications easily or in an organized/standard way.
Increase code re-usability.
Also reduce maintenance cost etc..

Object Oriented Programming Basic: PHP


[youtube https://www.youtube.com/watch?v=0smq5Lf6Q2k]

YouTube Link: https://www.youtube.com/watch?v=0smq5Lf6Q2k [Watch the Video In Full Screen.]



Why OOP in PHP ?
Most web projects still use procedural i.e., function based software development approach. And honestly, it has no issue, because most web projects are so small scale and straight forward that they don’t require OOP in most cases.

But for complex application development, you need OOP for effectiveness.
Like, if you want to build a home, you need a lot of planning, preparation and some standard approach to build it.

Fetch JSON Data Using jQuery AJAX Method: getJSON

Video tutorial illustrates fetching of JSON data using jQuery AJAX method, getJSON
Since its an AJAX method, the data is fetched without the need for refresh of the browser.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head><title>JSON jQuery AJAX</title></head>
<body>
 
<ul></ul>
 
<button>Users</button>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here we have a unordered list, without any list items in it. We’ll be fetching the list items from the JSON file using jQuery.
A button, clicking upon which we would fetch the Data inside jSON file.

JSON File
json_data.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
   "p1": { 
           "name": "Satish",
          "age":   25,
          "company": "Techntoip"
         },
 
 
   "p2": {
           "name": "Kiran",
          "age":   28,
          "company": "Oracle"   
         }   
}

Starts with a opening brace and ends with a opening brace.
In our example, we have taken two objects.
p1 and p2 are keys. It’s values are present inside opening and closing brace.
Each object has name, age and company info.

Also watch: Objects, Arrays: JSON Using jQuery.

jQuery Code
my_script.js

1
2
3
4
5
6
7
$("button").click( function() {
 $.getJSON( "json_data.json", function(obj) { 
  $.each(obj, function(key, value) { 
         $("ul").append("<li>"+value.name+"</li>");
  });
 });
});

Once the user clicks on the button, we invoke $.getJSON method.
First parameter we are passing is the URL of the json file. Next the call back function.

The call back function receives the jSON data which we have called as obj in our example.
Using $.each() method we iterate through all the objects present in our json file and then split them into key => value pair.

Now using the value we fetch the name present inside each objects value.

Video Tutorial: Fetch JSON Data Using jQuery AJAX Method: getJSON


[youtube https://www.youtube.com/watch?v=pe6keTE9LbE]

YouTube Link: https://www.youtube.com/watch?v=pe6keTE9LbE [Watch the Video In Full Screen.]




jSON & Database
We can generate jSON data out of a database and then fetch it using jQuery and display it on our web browser without the need for the modification of any code.
Whenever the json file or the database table data gets updated/modified, it instantly reflects on our web application.

Note:
You must open the file from a server. localhost works file too.
If you access the files directly from your computer folder, this application doesn’t work. So the files MUST be on a server.

Objects, Arrays: JSON Using jQuery

Video tutorial illustrates the basics of JSON: Create Object, Arrays, Access Elements, Modify/Update the value etc.

JSON full form: JavaScript Object Notation.

JSON is a lightweight data-interchange format.
It’s easy for humans to read and write.
It’s easy for machines to parse and generate.
So it’s more efficient at transferring data than XML.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
<html>
<head><title>JSON and jQuery!</title></head>
<body>
 
<ul></ul>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

We have a simple HTML structure, with a unorder list.
We’ll fill the list items from the JSON data using jQuery.

JSON and jQuery
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
$(document).ready( function() {
 
 var v1 = { "name": "Satish", "age": 25, "company": "Technotip IT Solutions" };
 var v2 = { "name": "Kiran", "age": 28, "company": "Oracle" };
 
 var obj = { "obj1": v1, "obj2": v2};
 
 var v3 = { "companies": [ "Microsoft", "Apple", "Google", "Oracle" ] };
 
  $("ul").append("<li>"+obj["obj1"]["name"]+"</li>");
  $("ul").append("<li>"+v3.companies[0]+"</li>");
});

Object
An object is a set of name/value pairs. An object begins with { and ends with }. Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

Array
An array is an ordered collection of values. An array begins with [ and ends with ]. Values are separated by , (comma).
Values in JSON can be string, number, array, objects, Boolean values or even null.

Fetch JSon Data From Object:
Object_name.Key;

Fetch JSon Data From Array:
Object_name.array_name[index_number];

Update JSON Data:

JSON and jQuery
my_script.js

1
2
3
4
5
 var v2 = { "name": "Kiran", "age": 28, "company": "Oracle" };
  $("ul").append("<li>"+v2.company+"</li>");
 
 v2.company = "Apple";
  $("ul").append("<li>"+v2.company+"</li>");

Would output
Oracle
Apple

Similarly, we could change the value of any key of an object or an array element.

Video Tutorial: Objects, Arrays: JSON Using jQuery


[youtube https://www.youtube.com/watch?v=MK39DQabaW8]

YouTube Link: https://www.youtube.com/watch?v=MK39DQabaW8 [Watch the Video In Full Screen.]



We could nest objects inside objects or arrays inside objects or objects inside an array etc, upto any level of complexities.
This is advantages for web applications like building menus with nested items, which are fetched from database.

Since, writing and fetching and parsing of JSON data is easy, most developers have stared using JSON over XML.

Moving Image Inside HTML page: Javascript ( A Small Fun Application )

Write a xHTML program to take input from the user and move the image to the corresponding location(position), using Javascript.

Note: ( CSS – Cascading StyleSheet )
Static Positioning does not have top and left properties, so an image which is positioned as Static can’t be moved.
Absolute positioning: The image moves to the new location according to the values of top and left.
Relative positioning: Here the image moves relative to its original position. From its original position, it applies the new top and left value and moves accordingly.

Video Explaining The Code:



YouTube Link: https://www.youtube.com/watch?v=cJtMtd2QmMM [Watch the Video In Full Screen.]



Write a xhtml program, and use the form input tags and accept two values from the user. Using document.getElementById, get those user entered values and assign it to two variables.
Similarly, using the div tags id, change the style information and assign the user entered values to div tags top and left position whenever user hits the “move” button.

Source Code: (move.html)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
<html>
 <head><title> Move Image </title>
 
 <style type="text/css">
  #kids { position: relative; top: 200px; left: 400px; }
 </style>
 
 <script type="text/javascript">
 
  function moveIt()
 {
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
 
var kids = document.getElementById("kids").style;
 
kids.top = x + "px";
kids.left = y  + "px";
 
 }
 
 </script>
 </head>
 <body>
 
<form>
X axis: <input type="text" id="x"><br />
Y axis: <input type="text" id="y"><br />
<input type="button" value=" Move " onclick="moveIt()" >
</form>
 
<div id="kids">
  <img 
  src="http://technotip.org/wp-content/themes/NewsDen/images/logo.gif" 
  width="220" height="42">
</div>
 
 </body>
</html>

Fun Application Code:
We have made some minor changes to the above code to get the x and y co-ordinates from the cursor position automatically.

Here, we do not accept input directly from the user. We have removed the html form using html comments(

<!--  Comments -->

) and invoke the javascript function moveIt when the user moves his mouse on the html document.
When there is onmousemove event, most browsers automatically throw some objects and we accept it in our function(as parameter) and make use of it. Some browsers like Microsoft’s Internet Explorer do not throw the event object automatically, so we assign it manually using the below code

   if( !evnt )
evnt = window.event;

Explanation of above two lines of code:
If evnt does not exist, then assign the event to evnt variable.

Also Make Sure To Watch This Video: Event Object: Javascript

Now using the clientX and clientY or screenX and screenY property of the event object, we track the x and y co-ordinates of the cursor and assign that value to the top and left position of the image(div tag which wraps the image tag).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
 
<html>
 <head><title> Move Image </title>
 
 <style type="text/css">
  #kids { position: relative; top: 200px; left: 400px; }
#x, #y { font-size: 24pt; color: red; }
 </style>
 
 <script type="text/javascript">
 
document.onmousemove = moveIt;
 
  function moveIt(evnt)
 {
if( !evnt )
evnt = window.event;
 
var x = evnt.clientX;
var y = evnt.clientY;
 
var kids = document.getElementById("kids").style;
 
kids.top = x + "px";
kids.left = y  + "px";
 
document.getElementById("x").innerHTML = x;
document.getElementById("y").innerHTML = y;
 
 
 }
 
 </script>
 </head>
 <body>
X:<span id="x"></span><br />
Y:<span id="y"></span>
<!--
<form>
X axis: <input type="text" id="x"><br />
Y axis: <input type="text" id="y"><br />
<input type="button" value=" Move " onclick="moveIt()" >
</form>
-->
<div id="kids">
 <img 
 src="http://technotip.org/wp-content/themes/NewsDen/images/logo.gif" 
 width="220" height="42">
</div>
 
 </body>
</html>

Hence, whenever the user move his mouse pointer over the html document the image starts moving according to the new value generated for the each move.