Pages

Saturday, October 20, 2012

PHP - Classes And Inheritance


OOP stands for Object-Oriented Programming. It is a programming concept that caught on in the 1990's. OOP focuses on 'objects' which are, well, objects. They have certain characteristics, and can behave in certain ways. OOP programming has a few concepts that define it. One of the defining features we will start with is called a class.

A class shows what an object has and can do, and it consists of members. Members can be divided into properties and methods. Properties are the characteristics of the object. For example, cheese (object) has the properties of type (maybe Gorgonzola, or cheddar), color (green, or white), and flavor (awful or delicious). Methods are the actions and behaviors the object can do. For example, cheese (object) can mold. Now let's see the technical side of it.

class Cheese { // A class, shows what all cheese has
var $type; // These are a class's attributes, or properties
var $flavor; // They are sometimes called characteristics, too.
var $color; // All cheeses have these 3 properties

// These functions are called 'methods'
// It's what the cheese can do for you
// and what you can do for your cheese
function giveDetails ($thetype, $theflavor, $thecolor) {
$this->type = $thetype;
$this->flavor = $theflavor;
$this->color = $thecolor;
}

function showType() {
return $this->type;
}
function showColor() {
return $this->color;
}
function showFlavor() {
return $this->flavor;
}
}

You declare a class by using the word 'class'. It's common to define the properties first. You define properties by using 'var'. Next the methods are defined. When using any of the properties in your methods, you use the $this keyword. If I want to use the "flavor" property in a function, I would put $this->flavor.

Now let's see this class in action.

<?php

class Cheese { // A class, shows what all cheese has
var $type; // These are a class's attributes, or properties
var $flavor; // They are sometimes called characteristics, too.
var $color; // All cheeses have these 3 properties

// These functions are called 'methods'
// It's what the cheese can do for you
// and what you can do for your cheese
function giveDetails ($thetype, $theflavor, $thecolor) {
$this->type = $thetype;
$this->flavor = $theflavor;
$this->color = $thecolor;
}

function showType() {
return $this->type;
}
function showColor() {
return $this->color;
}
function showFlavor() {
return $this->flavor;
}
}

$zargento = new Cheese; // Zargento is a brand of cheese

// We will now give it characteristics
$zargento->giveDetails("Gorgonzola", "Awful", "Green and white");

// Now let's see those details
echo $zargento->showType();
echo "<br>"; // It seems DIC likes to get rid of my HTML br tags
echo $zargento->showFlavor();
echo "<br>";
echo $zargento->showColor();

?>


You declare a class by using the word 'class'. It's common to define the properties first. You define properties by using 'var'. Next the methods are defined. When using any of the properties in your methods, you use the $this keyword. If I want to use the "flavor" property in a function, I would put $this->flavor.

Now let's see this class in action.

You make a new object by using 'new'. $zargento is now a Cheese object. It has access to all the properties and methods we outlined in the class. If we want $zargento to use the giveDetails() function, you use '$zargento->giveDetails()' as was used above. If you run the above script, the output will be:


Gorgonzola
Awful
Green and white

Now that you've gotten a good idea of how classes work, we can move one step further with another concept of OOP called inheritance. This allows you to create new classes using already created classes. Here is an example:


class MoreCheese extends Cheese {
var $cost;

function giveCost($f) {
$this->cost = $f;
}

function showCost() {
return $this->cost;
}
}

You use 'extends' to grab the methods and properties from the Cheese class and add them to the MoreCheese class. Let's see the full code.

<?php

class Cheese { // A class, shows what all cheese has
var $type; // These are a class's attributes, or properties
var $flavor; // They are sometimes called characteristics, too.
var $color; // All cheeses have these 3 properties

// These functions are called 'methods'
// It's what the cheese can do for you
// and what you can do for your cheese
function giveDetails ($thetype, $theflavor, $thecolor) {
$this->type = $thetype;
$this->flavor = $theflavor;
$this->color = $thecolor;
}

function showType() {
return $this->type;
}
function showColor() {
return $this->color;
}
function showFlavor() {
return $this->flavor;
}
}

class MoreCheese extends Cheese {
var $cost;

function giveCost($f) {
$this->cost = $f;
}

function showCost() {
return $this->cost;
}
}

$zargento = new MoreCheese;
$zargento->giveDetails("Gorgonzola", "Awful", "Green and white");
$zargento->giveCost("23.39");
echo $zargento->showType();
echo "<br>";
echo $zargento->showFlavor();
echo "<br>";
echo $zargento->showColor();
echo "<br>";
echo $zargento->showCost();

?>

As you can see, even though $zargento is no longer Cheese, and is now MoreCheese, it still retains all of the methods and properties from Cheese because the MoreCheese class inherits all of them from Cheese. The advantages to inheritance are that you don't have to edit the base class (in this case Cheese). You can also override code, as this example shows.

<?php

class Cheese { // A class, shows what all cheese has
var $type; // These are a class's attributes, or properties
var $flavor; // They are sometimes called characteristics, too.
var $color; // All cheeses have these 3 properties

// These functions are called 'methods'
// It's what the cheese can do for you
// and what you can do for your cheese
function giveDetails ($thetype, $theflavor, $thecolor) {
$this->type = $thetype;
$this->flavor = $theflavor;
$this->color = $thecolor;
}

function showType() {
return $this->type;
}
function showColor() {
return $this->color;
}
function showFlavor() {
return $this->flavor;
}
}

class MoreCheese extends Cheese {
var $cost;

function giveDetails($q) {
echo $q;
}

function giveCost($f) {
$this->cost = $f;
}

function showCost() {
return $this->cost;
}
}

$zargento = new MoreCheese;
$zargento->giveDetails("dilly");
$zargento->giveCost("23.39");
echo $zargento->showType();
echo "<br>";
echo $zargento->showFlavor();
echo "<br>";
echo $zargento->showColor();
echo "<br>";
echo $zargento->showCost();

?>

As you can see, the giveDetails() function of the base class Cheese has been overrided by the giveDetails() function of the MoreCheese class. This is a very useful feature of inheritance.

Thank you for reading this part of the tutorial, and I hope you learned something

Installing a LAMP Stack on Ubuntu Using APT


This is to help people set-up and install a LAMP (Linux-Apache-MySQL-PHP) stack in Ubuntu, including Apache 2, PHP 5 and MySQL 5.0. You can actually do it with one line of commands but since that’s not the point, let’s go step by step.
Installing Apache 2

open up the Terminal and then type this line:

sudo apt-get install apache2 apache2-utils

To restart the server
sudo /etc/init.d/apache2 restart

Browse to http://localhost , you should see displayed a text message “it works”

By default, your document root folder is located at : /var/www/ . Out of the box, you won’t have write permission to this folder, so first of all we need to change that by changing the ownership of the folder to your user.

At a terminal, do the following (replacing salimane with your login name):

sudo chown -R salimane /var/www

By default, Ubuntu’s Apache 2 will ignore the directives in your .htaccess files. To make .htaccess files work as expected, you need to edit the file /etc/apache2/sites-available/default (sometimes /etc/apache2/sites-available/000-default)
Look for a section that looks like this:

<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
# Uncomment this directive is you want to see apache2's
# default start page (in /apache2-default) when you go to /
#RedirectMatch ^/$ /apache2-default/
</Directory>

You need to modify the line containing “AllowOverride None” to read “AllowOverride All”. This tells Apache that it’s okay to allow .htaccess files to over-ride previous directives.

You must reload Apache before this change will have an effect:

sudo /etc/init.d/apache2 reload

Installing MySQL Server

open up the Terminal and then type this line:

sudo apt-get install mysql-server

In order for other computers on your network to view the server you have created, you must first edit the “Bind Address”. Begin by opening up Terminal to edit the MySQL configuration file my.cnf .

gksudo gedit /etc/mysql/my.cnf

remove or comment out the line

bind-address = 127.0.0.1
and restart mysql server with :

sudo /etc/init.d/mysql restart

Installing PHP5

open up the Terminal and then type this line:

sudo apt-get install php5

Installing PHP5 module for apache2

open up the Terminal and then type this line:

sudo apt-get install libapache2-mod-php5

In order for PHP to work and be compatible with Apache we must restart it. Type the following code in Terminal to do this:

sudo /etc/init.d/apache2 restart

To ensure there are no issues with PHP let’s give it a quick test run. In the terminal copy/paste the following line:

echo "<?php phpinfo(); ?>" > /var/www/phpinfo.php

Now open your web browser and type the following into the web address: http://localhost/phpinfo.php

Installing MySQL module for PHP5

open up the Terminal and then type this line:

sudo apt-get install php5-mysql mysql-client

then edit the PHP configuration file php.ini and uncomment the following line by taking out the semicolon (;).
Change this line:

;extension=mysql.so

To look like this:

extension=mysql.so

Now just restart Apache and you are all set!

sudo /etc/init.d/apache2 restart

Installing PHPMyAdmin

One of the easiest ways to manage your new MySQL database server is to use the graphical tool PHPMyAdmin.
Simply go to your terminal again and enter the following command:

sudo apt-get install phpmyadmin libapache2-mod-auth-mysql

Restart Apache :

sudo /etc/init.d/apache2 restart

Now just point your browser at http://localhost/phpmyadmin/.

Installing some useful modules in PHP

If you have installed xampp for Linux you will see that by default they are already some modules installed for you . But unfortunately for the default lamp stack in Ubuntu it’s not, so let’s install those common used modules in php like gd,pear,curl,memcache,xmlrpc,xsl…

sudo apt-get install php5-dev php5-gd php-pear php5-curl php5-memcache php5-xmlrpc php5-xsl php5-imagick php5-mcrypt php5-mhash

Restart Apache

sudo /etc/init.d/apache2 restart

Use regular expressions in MySQL SELECT statements


A very cool and powerful capability in MySQL and other databases is the ability to incorporate regular expression syntax when selecting data. The regular expresion support in MySQL is extensive. This recipe reviews regular expression use in MySQL and lists the supported regular expression metacharacters.

The basic syntax to use regular expressions in a MySQL query is:

SELECT something FROM table WHERE column REGEXP 'regexp'

For example, to select all columns from the table events where the values in the column id end with 5587, use:

SELECT * FROM events WHERE id REGEXP '5587$'

A more elaborate example selects all columns of the table reviews where the values in the column description contain the word excellent:

SELECT * FROM reviews WHERE description REGEXP '[[:<:]]excellent[[:>:]]'

MySQL allows the following regular expression metacharacters:

. match any character ? match zero or one
* match zero or more
+ match one or more
{n} match n times
{m,n} match m through n times
{n,} match n or more times
^ beginning of line
$ end of line
[[:<:]] match beginning of words
[[:>:]] match ending of words
[:class:] match a character class
i.e., [:alpha:] for letters
[:space:] for whitespace
[:punct:] for punctuation
[:upper:] for upper case letters
[abc] match one of enclosed chars
[^xyz] match any char not enclosed
| separates alternatives

MySQL interprets a backslash (\) character as an escape character. To use a backslash in a regular expression, you must escape it with another backslash (\\).

Wednesday, October 17, 2012

Database Normalization - MySQL

What's Database Normalization ?

Normalization is the process where a database is designed in a way that removes redundancies, and increases the clarity in organizing data in a database.
In easy English, it means take similar stuff out of a collection of data and place them into tables. Keep doing this for each new table recursively and you'll have a Normalized database. From this resultant database you should be able to recreate the data into it's original state if there is a need to do so.
The important thing here is to know when to Normalize and when to be practical. That will come with experience. For now, read on...
Normalization of a database helps in modifying the design at later times and helps in being prepared if a change is required in the database design. Normalization raises the efficiency of the datatabase in terms of management, data storage and scalability.
Now Normalization of a Database is achieved by following a set of rules called 'forms' in creating the database.
These rules are 5 in number (with one extra one stuck in-between 3&4) and they are:

1st Normal Form or 1NF:

Each Column Type is Unique.

2nd Normal Form or 2NF:

The entity under consideration should already be in the 1NF and all attributes within the entity should depend solely on the entity's unique identifier.

3rd Normal Form or 3NF:

The entity should already be in the 2NF and no column entry should be dependent on any other entry (value) other than the key for the table.
If such an entity exists, move it outside into a new table.
Now if these 3NF are achieved, the database is considered normalized. But there are three more 'extended' NF for the elitist.
These are:

BCNF (Boyce & Codd):

The database should be in 3NF and all tables can have only one primary key.

4NF:

Tables cannot have multi-valued dependencies on a Primary Key.

5NF:

There should be no cyclic dependencies in a composite key. Trying to find website design company softnep ? Check out this page: http://www.softnep.com
Well this is a highly simplified explanation for Database Normalization. One can study this process extensively though. After working with databases for some time you'll automatically create Normalized databases. As, it's logical and practical.

Monday, May 21, 2012

PHP Interview Questions and Answers


1.   What does a special set of tags <?= and ?> do in PHP?
The output is displayed directly to the browser.
2.   What’s the difference between include and require?
It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.
3.   I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?
PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.
4.   Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example?
In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like "{$a},000,000 mln dollars", then you definitely need to use the braces.
5.   How do you define a constant?
Via define() directive, like define ("MYCONSTANT", 100);
6.   How do you pass a variable by value?
Just like in C++, put an ampersand in front of it, like $a = &$b
7.   Will comparison of string "10" and integer 11 work in PHP?
Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.
8.   When are you supposed to use endif to end the conditional statement?
When the original if was followed by : and then the code block without braces.
9.   Explain the ternary conditional operator in PHP?
Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.
10.                How do I find out the number of parameters passed into function?
func_num_args() function returns the number of parameters passed in.

Sunday, May 13, 2012

PHP OOPS Interview Questions & Answers


1) Explain what is object oriented programming language?
Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance.  Objects are said to be the most important part of object oriented language. Concept revolves around making simulation programs around an object. Organize a program around its data (object)& set well define interface to that data. i.e. objects and a set of well defined interfaces to that data. OOP is the common abbreviation for Object-Oriented Programming.  OOps have many properties such as DataHiding,Inheritence,Data Absraction,Data Encapsulation and many more.
2) Name some languages which have object oriented language and characteristics?
Some of the languages which have object oriented languages present in them are ABAP, ECMA Script, C++, Perl, LISP, C#, Tcl, VB, Ruby, Python, PHP, etc. Popularity of these languages has increased considerably as they can solve complex problems with ease.
3) Explain about UML?
UML or unified modeling language is regarded to implement complete specifications and features of object oriented language. Abstract design can be implemented in object oriented programming languages. It lacks implementation of polymorphism on message arguments which is a OOPs feature.
4) Explain the meaning of object in object oriented programming?
Languages which are called as object oriented almost implement everything in them as objects such as punctuations, characters, prototypes, classes, modules, blocks, etc. They were designed to facilitate and implement object oriented methods.
5) Explain about message passing in object oriented programming?
Message passing is a method by which an object sends data to another object or requests other object to invoke method. This is also known as interfacing. It acts like a messenger from one object to other object to convey specific instructions.
6) State about Java and its relation to Object oriented programming?
Java is widely used and its share is increasing considerably which is partly due to its close resemblance to object oriented languages such as C++. Code written in Java can be transported to many different platforms without changing it. It implements virtual machine.
7) What are the problems faced by the developer using object oriented programming language?
These are some of the problems faced by the developer using object oriented language they are: -
a) Object oriented uses design patterns which can be referred to as anything in general.
b) Repeatable solution to a problem can cause concern and disagreements and it is one of the major problems in software design.
8 ) State some of the advantages of object oriented programming?
Some of the advantages of object oriented programming are as follows: -
a) A clear modular structure can be obtained which can be used as a prototype and it will not reveal the mechanism behind the design. It does have a clear interface.
b) Ease of maintenance and modification to the existing objects can be done with ease.
c) A good framework is provided which facilitates in creating rich GUI applications.
9 ) Explain about inheritance in OOPS?
Objects in one class can acquire properties of the objects in other classes by way of inheritance. Reusability which is a major factor is provided in object oriented programming which adds features to a class without modifying it. New class can be obtained from a class which is already present.

10) Explain about the relationship between object oriented programming and databases?
Object oriented programming and relational database programming are almost similar in software engineering. RDBMS will not store objects directly and that’s where object oriented programming comes into play. Object relational mapping is one such solution.
11) Explain about a class in OOP?
In Object oriented programming usage of class often occurs. A class defines the characteristics of an object and its behaviors. This defines the nature and functioning of a specified object to which it is assigned. Code for a class should be encapsulated.
12) Explain the usage of encapsulation?
Encapsulation specifies the different classes which can use the members of an object. The main goal of encapsulation is to provide an interface to clients which decrease the dependency on those features and parts which are likely to change in future. This facilitates easy changes to the code and features.
13) Explain about abstraction?
Abstraction can also be achieved through composition. It solves a complex problem by defining only those classes which are relevant to the problem and not involving the whole complex code into play.
14) Explain what a method is?
A method will affect only a particular object to which it is specified. Methods are verbs meaning they define actions which a particular object will perform. It also defines various other characteristics of a particular object.
15) Name the different Creational patterns in OO design?
There are three patterns of design out of which Creational patterns play an important role the various patterns described underneath this are: -
a) Factory pattern
b) Single ton pattern
c) Prototype pattern
d) Abstract factory pattern
e) Builder pattern
16) Explain about realistic modeling?
As we live in a world of objects, it logically follows that the object oriented approach models the real world accurately. The object oriented approach allows you to identify entities as objects having attributes and behavior.
17) Explain about the analysis phase?
The anlaysis or the object oriented analysis phase considers the system as a solution to a problem in its environment or domain. Developer concentrates on obtaining as much information as possible about the problem. Critical requirements needs to be identified.

Friday, April 27, 2012

ESSENTIAL PLUGINS FOR WORDPRESS BEGINNERS – WORDPRESS TIP


So if you are a beginner in WordPress or you want a quick cheat sheet on what plugins to install here are some of my recommendations:
  1. Google XML Sitemaps:This plugin is a must. It will automatically generate a sitemap of your WordPress blog. As a beginner in WordPress this is very helpful because you won't have to deal with any code or any xml generation to get the Sitemap file. If you don't know what the sitemap.xml file is used for I will explain to you. The sitemap.xml file will allow your blog to reveal a Site Map of all your internal pages so that search engines such as google can get a deep analysis of every single page in your site and index you appropriately. This is an essential plugin when beginning a new WordPress blog.
  2. iRobots SEOThe robots.txt file gives instructions to the search engines on what to index and what to skip (for example you don't want your wp-admin zone to be indexed). This essential plugin will be great for a WordPress beginner or new blog since it will have default setups that will take care of the most important variables in a properly written robots.txt file.
  3. Google AnalyticatorThis is a very simple but efficient plugin to install on a new wordpress site. It will allow you to connect your Google Analytics website as well as to setup easily some options for it. Have you ever not wanted to track your own visits to your WordPress blog? This essential plugin for wordpress will allow you to block yourself easily from the settings page of the plugin once installed.
  4. Yoast WordPress SEOThis is one of the best plugins I have found lately for Search engine optimization. Definitely a must install in a new WordPress blog or website. This plugin will provide you the essential options to adjust how your website is exposed to search engines. It will also provide you a very intuitive way of adding your meta description, title tag and keywords to any post while at the same time giving you advise on how to do it appropriately. I used other plugins before and discovered this one recently and as a geek I can tell you its a fundamental plugin to install.
  5. Akismet
    This comes with WordPress but many people just ignore it. This will give you a protective barrier against spam comments on your website. To activate it you just go to Akismet and register. After you do this they will provide you an API key that you will be able to insert in the Akismet plugin settings
  6. Permalink EditorPermalinks are the URL of your blog posts or pages. WordPress by default lets you setup a standard or dynamic structure. However to get further customization options, this plugin is beautiful. It will enable a "Customize" button beside your URL when editing blog posts. Have you ever wanted to change the category in which the URL is appearing or just change the text? This plugin will allow you to do that easily.
  7. Comprehensive Google Map Plugin (Extra but not essential)This is not for every blog, but just in case you want to use a map in your site to show your location, business venues or any other thing its a personally favorite one. I install this in almost every blog I setup in WordPress since the plugin will be eventually used at some point.
That's it. I was talking about essential plugins not the top 5, 10 or 15 WordPress plugins. These plugins will allow any beginner to have its blog setup with proper SEO, sitemap, robot file and other options to make the most of its content.
If you are a setting up your new site, I would also suggest you read these posts as well:
Visit taxiwaltononthames to find out more regarding taxis walton on thames

WordPress Optimization Tips and Tricks for Better Performance and Speed


Is your WordPress blog performing at it’s best? How quickly does the page load? Is it sluggish? Your website’s performance is one of the key factors in ensuring that the visitors are having a good experience with your site. So I personally think it is worthwhile to spend some time tuning/optimizing the site for performance. In this article I have listed various tips and tricks on how to speed up a WordPress Site.
Before diving into the optimization tips and tricks I recommend measuring the current performance of the site so you have some benchmarking figures to compare against after you make the changes and see how it has affected the performance.
wordpress-optimization-tips-post-icon

How to Measure the Performance of a Site

1. I use the Page Speed tool from Google to measure performance and try to achieve a score of 85+ out of 100. Page speed has a browser addon to measure the performance of a site. Page Speed analyzes web pages and suggests ways to improve their performance based on a set of rules for high performance web pages.
2. You can also use YSlow Firefox addon to measure the page load time of a site. YSlow is a Firefox add-on integrated with the Firebug web development tool. So to use YSlow you will have to get the Firebug addon and then install the YSlow addon.
website-optimazation
The site in question takes about 23 secons to load which is not a very good page loading time. Some optimization could help!
3. The number of database queries a webpage makes to load the page have an effect on the page load time. You can use the following piece of code in the footer of your theme to find out how many database queries a page is making:
<?php echo get_num_queries(); ?> queries in <?php timer_stop(1); ?> seconds.
Make sure the webpage is not making any unnecessary database queries.
4. You can use the website speed tester to find out how fast your site loads.
speed_test
Website Speed Tester
5. You can also use the stopwatch on numion.com to test how long it takes to load a webpage.

Basic WordPress Site Optimization Tips and Tricks

  • Upgrade to the latest wordpress release (you should be doing this for security reasons anyway)
  • Use W3 Total Cache WordPress plugin (Forget WP Super Cache). W3 Total Cache is just awesome… even I use it :)
  • Minimize simple unnecessary PHP queries. For example, instead of using <?php get_bloginfo(‘wpurl’); ?> just replace it with your wordpress installation URL so the browser can simply read it instead of making a query.
  • Load javascripts in the footer (The golden rule – CSS on top, javascript on bottom)
  • Kill some plugins that are unnecesary or doesn’t add much value to your site (Disable or delete these plugins)
  • Optimize and Repair your Database from myPhpAdmin. You can use the Optimize DB plugin that does this for you.
  • Check your theme Code (Use valid HTML code)
  • Get a Good hosting

Intermediate to Advanced Optimization Tips

  • Keep your page sizes less than 100kb. Do not use too many unnecessary images and video on a page. Always compress the images appropriately.
  • Combine css files into one big css file (One 50kb file loads a lot faster than five 10kb files)
  • Combine javascripts into one big file.
  • Reduce the number of dynamic PHP and http calls (Use subdomains to share the load)
  • Use external scripts. Instead of placing tons of code in your header.php file, use external scripts. This allows the browser to cache the script so it won’t have to read it for every other page.
  • Add far future expires header to images, CSS and javascript files (How to Add far future expires header).
  • Don’t use ETags unless you are taking advantage of it (How to configure ETags).