Friday, August 26, 2011

MYSQL Optimization and increase performance

Optimize SQL Queries:  

  1. Indexes 
  2. Symbol Operator 
  3. Wildcard 
  4. NOT Operator 
  5. COUNT VS EXIST 
  6. Wildcard VS Substr 
  7. Index Unique Column
  8. Max and Min Operators 
  9. Data Types 
  10. Primary Index
  11. String indexing 
  12. Limit The Result 
  13. In Subquery
  14. union vs OR

Indexes 



To create Index for your column is a common way to optimize your search result. 

Symbol Operator



Symbol operator such as >,<,=,!=, etc. are very helpful in our query. We can optimize some of our query with symbol operator provided the column is indexed.


example:
SELECT * FROM TABLE WHERE COLUMN > 16
SELECT * FROM TABLE WHERE COLUMN >= 15


Wildcard


In SQL, wildcard is provided for us with ‘%’ symbol. Using wildcard will definitely slow down.

We can optimize our query with wildcard by doing a postfix wildcard instead of pre (or) full wildcard. 


Note: That column must be indexed for such optimize to be applied

#Full wildcard  SELECT * FROM TABLE WHERE COLUMN LIKE '%hello%'; 


#Postfix wildcard
 SELECT * FROM TABLE WHERE COLUMN LIKE 'hello%';


#Prefix wildcard
 SELECT * FROM TABLE WHERE COLUMN LIKE '%hello'; 



NOT Operator

To Avoid NOT operator in SQL. 


  • Positive Operator much faster than negative operator. 
  • Using a positive operator just stop immediately once the result has been found. But negative operator check the all the records



Positive operators: 
LIKE, IN, EXIST (or) = symbol operator

Negative operator:

NOT LIKE, NOT IN, NOT EXIST or != symbol. 



COUNT VS EXIST


"To use Exist operator instead of Count operator" to determine whether a particular data exist.


SELECT COLUMN FROM TABLE WHERE COUNT(COLUMN) > 0


  • The above query is very bad query since count will search for all record exist on the table to determine the numeric value of field ‘COLUMN’. 
  • The better alternative will be to use the EXIST operator where it will stop once it found the first record. Hence, it exist.

Wildcard VS Substr



"To use wildcard instead of substr". The column should be indexed for using wildcard.

SEARCH FOR ALL ROWS WITH THE FIRST CHARACTER AS 'E'

#BAD
 SELECT * FROM TABLE WHERE substr ( COLUMN, 1, 1 ) = 'E'.

#BETTER
 SELECT * FROM TABLE WHERE COLUMN = 'E%'.


Index Unique Column



  • MySQL search better with column that are unique and indexed. 
  • Hence, it is best to remember to index those columns that are unique.


Max and Min Operators



Using Max and Min operators should help speed up the searching. If you are going to use min and max, The column must be indexed

Data Types


  • Use the most efficient (smallest) data types possible. 
  • VARCHAR will be better than long text to store an email or small details.


Primary Index


The primary column that is used for indexing should be made as short as possible. This makes identification of each row easy and efficient by the DBMS.


String indexing


  • It is unnecessary to index the whole string when a prefix or postfix of the string can be indexed instead. 
  • Especially if the prefix or postfix of the string provides a unique identifier for the string, it is advisable to perform such indexing. 
  • Shorter indexes are faster, not only because they require less disk space, but because they also give you more hits in the index cache, and thus fewer disk seeks.



Limit The Result

Another common way of optimizing your query is to minimize the number of row return. 


SELECT * FROM TABLE

SELECT * FROM TABLE WHERE 1 LIMIT 10



In Subquery



Using dummy table is better than using an IN operator. Alternative, an exist
operator is also better.

SELECT * FROM TABLE WHERE COLUMN IN (SELECT COLUMN FROM TABLE)

Doing this is very expensive because SQL query will evaluate the outer query first before proceed with the inner query. Instead we can use this instead.

SELECT * FROM TABLE, (SELECT COLUMN FROM TABLE) as dummytable WHERE dummytable.COLUMN = TABLE.COLUMN;


Utilize Union instead of OR


Indexes lose their speed advantage when using them in OR ­situations in MySQL at least. Hence, this will not be useful although indexes is being applied

SELECT * FROM TABLE WHERE COLUMN_A = 'value' OR COLUMN_B = 'value'

Union: run faster

SELECT * FROM TABLE WHERE COLUMN_A = 'value'
UNION
SELECT * FROM TABLE WHERE COLUMN_B = 'value'





SQL Performance Tips

  1. use index in the column.
  2. use primary index.
  3. use index unique
  4. use symbol operators like, <,>,=
  5. use positive operator like IN, EXIST instead of NOT IN, NOT EXIST
  6. use full/pre wildcard operator
  7. use prefix/postfix string index.
  8. use LIMIT operator.
  9. use EXIST instead of COUNT
  10. use small data types VARCHAR
  11. Use Slow Query Log (always have it on!)
  12. Don't use DISTINCT when you have or could use GROUP BY
  13. Use LOAD DATA instead of INSERT
  14. Don't use ORDER BY RAND() if you have > ~2K records
  15. Use SQL_NO_CACHE when you are Selecting frequently updated data or large sets of data.
  16. use UNION instead of OR
  17. Avoid using IN(...) when selecting on indexed fields, It will kill the performance of SELECT query.
  18. Use stored procedures to avoid bandwidth wastage
  19. enable key_buffer, query cache, table cache.

Simple example oops Definition

What is an Abstract Class?
An abstract class defines the basic skeleton for the class. It contains attributes and members but
some members are incomplete and is waiting for some other class to extend it through inheritance
so that the derived class provides a full functionality for the incomplete methods. A abstract class
cannot be instantiated and it can only be extended. A class prefix with “abstract” keywords are
abstract class. If a method is defined as abstract then it cannot be declared as private (it can only be
public or protected).
Syntax:
< ?
abstract class classname
{
//attributes and methods
.
.
abstract function methodname
}

class derived extends classname
{
function methodname
}
?>
Example 1 – Basic Abstract Class Usage
< ?
abstract class employee
{
protected $empname;
protected $empage;

function setdata($empname,$empage)
{
$this->empname = $empname;
$this->empage = $empage;
}

abstract function outputData();
}

//extending abstract class
class EmployeeData extends employee
{
function __construct($name,$age)
{
$this->setdata($name,$age);
}

function outputData()
{
echo $this->empname;
echo $this->empage;
}
}

$a = new EmployeeData("Hitesh","24");
$a->outputData();
?>
Output:
Hitesh
24
Explanation for the Example 1:
• Here i have made employee class an abstract class
• Employee class has 2 data members $empname and $empage. It also has a abstract method
outputData() and public method setData()
• Now i am extending the employee class in EmployeeData. It contains the functionality for
the abstract method outputData defined in employee class
Example 2 – Abstract Class Error
< ?
abstract class employee
{
protected $empname;
protected $empage;

function setdata($empname,$empage)
{
$this->empname = $empname;
$this->empage = $empage;
}

abstract function outputData();
}

class EmployeeData extends employee
{

function __construct($name,$age)
{
$this->setdata($name,$age);
}
}
$a = new EmployeeData("Hitesh","24");
$a->outputData();
//Will generate error as the EmployeeData class doesn't has the abstract
method defined
?>
Output
This will give you an error “Class EmployeeData contains 1 abstract method and must therefore be
declared abstract or implement the remaining methods (employee::outputData)”
Example3 – Multiple Abstract Class
< ?
abstract class employee
{
protected $empname;
protected $empage;

function setdata($empname,$empage)
{
$this->empname = $empname;
$this->empage = $empage;
}

abstract function outputData();
}

abstract class EmployeeData extends employee
{
abstract function setDataForEmployee();
}

class Payment extends EmployeeData
{
function setDataForEmployee()
{
//Functionality
}

function outputData()
{
echo "Inside Payment Class";
}
}

$a = new Payment();
$a->outputData();
?>
Output: “Inside Payment Class”


Interface :
This article will guide through the Interface Class in Object Oriented Programming. In simple
words Interface is a class with no data members and contains only member functions and they lack
its implementation. Any class that inherits from an interface must implement the missing member
function body. Interfaces is also an abstract class because abstract class always require an
implementation. In PHP 5 class may inherit only one class, but because interfaces lack an
implementation any number of class can be inherited. In PHP 5, interfaces may declare only
methods. An interface cannot declare any variables. To extend from an Interface, keyword
implements is used. PHP5 supports class extending more than one interface.
Syntax:
interface interfacename
{
function name()
function name1()
}

href='http://www.hiteshagrawal.com/php/oops-in-php5-polymorphism'>Polymorphism
in PHP5

class temp implements interfacename
{
public function name
{

}
}
Example1 – Interface Class in PHP5
< ?
interface employee
{
function setdata($empname,$empage);
function outputData();
}

class Payment implements employee
{
function setdata($empname,$empage)
{
//Functionality
}

function outputData()
{
echo "Inside Payment Class";
}
}

$a = new Payment();
$a->outputData();
?>
Output: “Inside Payment Class”
Explanation for the above Example:
Here i have a interface class called employee having two methods setData() and
outputData()
I am implementing the interface class on Payment class. Payment class also contains the
functionality for the methods defined in the interface.
Example2 – Combining Abstract Class and Interface Class
< ?
interface employee
{
function setdata($empname,$empage);
function outputData();
}

abstract class Payment implements employee //implementing employee interface
{
abstract function PaymentInfo();
}

class PaySlip extends Payment
{
function collectPaySlip()
{
echo "PaySlip Collected";
$this->outputData();
}

function outputData()
{
echo "Inside PaySlip Class";
}

function PaymentInfo()
{
echo "Inside PaySlip Class";
}

function setData($empname,$empage)
{
//Functionality
}
}
$a = new PaySlip();
$a->collectPaySlip();
?>
Output:
PaySlip Collected
Inside Payment Class


Inheritance :
This tutorial will guide you through one of the main feature of Object Oriented Programing which
is called Inheritance. Basically Inheritance is a mechanism where a new class is derived from the
existing base class. The derived class shares/inherit the functionality of the base class. To extend the
class behavior PHP5 have introduced a new keyword called “extends“.
While performing Inheritance operation Access Specifiers specify the level of access that the
outside world (other objects and functions) have on the data members / member functions of the
class. During Inheritance operation the derived class can access the parent class attributes having
protected/public access specifier. To access private data of parent class from derived class you will
have to call public/protected method of the parent class which will access the private variable and
return the data to the derived class. In PHP5 only single inheritance is allowed. i.e. You can inherit
only one class.
Example 1 – Parent Keyword in Inheritance Error
< ?
//Generates an error
class parent
{
private $firstname;
private $lastname;
}

class children extends parent
{
function __construct()
{
echo $this->firstname;
echo $this->lastname;
}
}
$a = new children();
?>
Output: Generate error in PHP5 as parent is keyword in PHP5.
Explanation: Parent is the Keyword in PHP5 and it cannot be used in PHP5 for declaring
classname.
Example 2 – Basic Inheritance Call
< ?
class parent1
{
protected $firstname = 11;
protected $lastname = 23;
}

class children extends parent1
{
function __construct()
{
echo $this->firstname;
echo $this->lastname;
}
}
$a = new children();
?>
Output: 1123
Explanation: Parent1 class have extending its functionality to the children class. Now the children class can access the
$firstname and $lastname attributes.
Example 3 – Accessing Private Data Member through Inheritance
< ?
class parent1
{
private $firstname = "hitesh";
protected $lastname = 23;

protected function getData()
{
return $this->firstname;
}
}

class children extends parent1
{
function __construct()
{
echo $this->getData();
}
}

$a = new children();
?>
Output: hitesh


OOPS in PHP 5 – Polymorphism

Polymorphism in PHP5 is a technique where the function to be called is detected based on the class object calling it at runtime. The basis of Polymorphism is Inheritance and function overridden.


Example – Basic Polymorphism

< ?

class BaseClass
{
public function myMethod()
{
echo "BaseClass method called";
}
}

class DerivedClass extends BaseClass
{
public function myMethod()
{
echo "DerivedClass method called";
}
}

function processClass(BaseClass $c)
{
$c->myMethod();
}

$c = new DerivedClass();
processClass($c);
?>

Output:
DerivedClass method called
Explanation:

Here i am declaring BaseClass and DerivedClass but i am calling the the processClass with the Derived Class Object.


Encapsulation

Encapsulation is just wrapping some data in an object. The term "encapsulation" is often used interchangeably with "information hiding".

<?php


class App {
private static $_user;

public function User( ) {
if( $this->_user == null ) {
$this
->_user = new User();
}
return $this->_user;
}

}

class User {
private $_name;

public function __construct() {
$this
->_name = "Joseph Crawford Jr.";
}

public function GetName() {
return $this->_name;
}
}

$app
= new App();

echo $app
->User()->GetName();

?>


Tuesday, August 23, 2011

Ajax - Basics code

Ajax - Basics code


<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>


Wednesday, August 17, 2011

OOPS with PHP

PHP oops:

**php class:

class is collection of variables and functions thats serves the common purpose. Class is user define datatypes.

Class has following members:

1. Attributes
2. Methods
exm:

class class_name
{
var $varibale = 'var_name';

function fn_name()
{
statement;
}
}

**Object:

To create Instance of class is a object.

Exm:
$object = new class_name();


y;
}

}

$a = new x();
$a = z();

?>
output : 10


**Inheritance:


Inheritance is the properties which one class share the data and methods of another class.

Inheritance is the process basing one class on another.

If you can write code once in its base class and reuse it derived class.

Base class provide methods, properties and other members to a derived class.



**Encapsulation:

The wrapping up of data and the methods into a single unit is called a encapsulation.

Encapsulation is a ability to hiding all the internal details of an object from outside only expose the data and method that are requiered.

Example:-cars and owners... all the functions of cars are encapsulated with the owners..

**Abstraction:

Show the neccessary details to the client of the object. The abstract class methods are must be implemented on derived class.

Example:-A simple example is using a base class "Animal", with a virtual function "Walk". In the case two-legged versus four-legged animals, both of them walk, but the actual mechanics are different. The "Walk" method abstracts the actual mechanics behind the walking that each "Animal" does. 2nd example:-A class called Animal. It has properties like ears,colour, eyes but they are not defined. It has methods like Running(), Eating(), etc. but the method does not have any body, just the definition.

**Interface:
Interface is a class that have many method and that method is only having declaration not having the implementation.
Interface has only a method declaration but no definition.

**Why we need interface

1. instead of multiple inheritance.(avoid multiple inheritance).
2. Use Inteface is common class for all other classes.
3. when you have two or more functionalities talking to each other that time we are going to interface.

**Single inheritance
One class inherited by only other one class.

**Multiple inheritance

One class inherited more than one class.

**Constructor
Constructor is a member fuction of the class, with name of the fuction is same as the class name.
The constructor is automatically invoke the instance of class(objects).

Answer2
class Point2D{
int x; int y;
public Point2D() : x(0) , y(0) {} //default (no argument) constructor
};

main(){

Point2D MyPoint; // Implicit Constructor call. In order to allocate memory on stack, the default constructor is implicitly called.

Point2D * pPoint = new Point2D(); // Explicit Constructor call. In order to allocate memory on HEAP we call the default constructor.
}

**Diff bw function and procedures

1. function can return values.
2. procedures can't return values.

**Polymorphism:
The ability to different objects to respond, to identical message its called polymorphism.
One name, multiple form.
One interface, multiple methods.

**PHP Polymorphism Function:
The PHP Polymorphism Method is one of the feature of OOP language. Generally we get polymorphism in two ways:
Compile time
Run time
Compile time polymorphism PHP is like function overloading, operator overloading etc. In Polymorphism function overloading we can create more than one function with same name but with different signature that means it could have different number of parameters, different datatype of the parameter etc. Depending on the actual number and/or the data type the compiler resolve the actual call .
In operator overloading predefined operators treat as functions and one object calls this function and passes another object as argument. PHP neither supports operator overloading nor function overloading.
Inheritance and virtual functions are the examples of PHP Run time polymorphism. PHP supports Inheritance as well as virtual function as function overriding.
Following examples will exemplify each of the types of polymorphism:
PHP Polymorphism Function Example:
";}}
class B extends A{
function Disp(){
echo "Inside the Chlid class
";}}
class C extends A{
}
$obj=new B();
$obj->Disp();
$obj2=new C();
$obj2->Disp();
?>

Output:
Inside the Chlid class
Inside the Base class



Difference bw web server and application server?
Webserver:

webserver serves the pages for viewing web browser using http protocal.
Webserver serves the static and dynamic pages using http protocal.
Webserver support only http protocal, And web application.

Application server:

Application server support all kind of protocals.
Application server handle business logic such as transaction and messaging.
Mysql 4 vs mysql5

main Reasons upgrading mysql 5:

1. stored procedure
2. trigger
3. Views

Enable subroutines :

To call to return values that you use another part of query.

Trigger:
More control the alteration made to a table.
Such as restrict access to specific data, perform logging and audit data modification.

Views:
Developers can use to show actual code directly from the screen of the client program this is used to debugging troubleshooting.

Why we are go innodb? Difference bw innodb and myisam?
Innodb:
1. innodb supports transaction.
2. Row-level locking.
3. foriegn key.
4. speed
5. data integirity(combination of differen table types in db)
6. Its Large data volumes.
7. innodb stores table and indexes in a table space.

Myisam:
1. Fast
2. Not supported foriegn key.
3. support small level data volumes
4. Each tables and indexes stored in seperate files.
5. Table level locking.

Row level locking vs table level locking?

Table level locking:

The data in one table modified by the other table. The entire table will locked for the next process.

Row-level locking:
Only the row of the table that is being updated is locked.

How to change default page in index.html other than index.php?

1. Change httpd.conf
2. DirectoryIndex index.php

or
(executed index.php if neither index.html and index.pl)
1. change .htaccess file
2. DirectoryIndex index.html index.pl /siva/index.php


Increase file size upload limit using php.ini or htaccess
Any php web application or server configured with default values set in php.ini and .htacess. Generally almost web hosting providers configures the web application to optimum settings, which effects server bandwidth, server memory limit, server disk space, and peak security measures. For file uploading and PHP script execution there is default configuration in PHP.ini. However almost hosting providers give chance to developer to customize this default configuration by override php.ini or. htaccess . some settings can be configured by ini_set() method at run time of script.
Default PHP.ini
;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = "${path}\tmp\"

; Maximum allowed size for uploaded files.
upload_max_filesize = 2M

;;;;;;;;;;;;;;;;;;;
; Resource Limits;
;;;;;;;;;;;;;;;;;;;

max_execution_time = 30 ; Maximum execution time of each script, in seconds
max_input_time = 60 ; Maximum amount of time each script may spend parsing request data
;max_input_nesting_level = 64 ; Maximum input variable nesting level
memory_limit = 128M ; Maximum amount of memory a script may consume (128MB)
Increasing file upload size by php.ini
File upload size affected by mainly below PHP settings.
file_uploads = On
This setting must be on. It allows running uploads through HTTP.
Ensure this value is on the value can be On/Off or 1/0 or true/false.
upload_max_filesize = 20M
This value limits the size of uploaded single file. Give it value what ever your requirements.
post_max_size = 40M
This value limits the size of all the uploaded content. For example upload_max_filesize is for single file, if we upload 3 files simultaneously each 15mb total 45mb so it exceeds post_max_size.
Remember post_max_size must be larger about 40% of upload_max_filesize.
max_execution_time = 30
Generally image uploading and manipulating with GD or Imagemagic consumes much time. So it may exceeds 30 seconds. You can modify whatever your requirements. When a script execution time exceeded by this limit the server stops the scripts or gives fatal error.
memory_limit = 128M
Generally image uploading and manipulation with GD or Imagemagic consumes much server memory. When it exceeds this memory the server stops executing the script, then we see empty page or no response from server or we get a fatal error.
Completed example, to increase 10Mb
upload_max_filesize = 10M ;
post_max_size = 20M ;
memory_limit = 128M
Copy the above settings into your php.ini and put it in your web root directory.
Increasing file upload size by .htaccess
php_value upload_max_filesize 10M
php_value post_max_size 20M
php_value memory_limit 128M
Copy the above settings into your .htaccess file and put it in your web root directory.
Almost all web host providers give to override the .htacces ,so you can use above method.

Tuesday, August 16, 2011

MVC architecture PHP

Model View Controller MVC:

1. Abstract
2. What is MVC
3. The Site Structure
4. The index file
5. The Registry
6. The Model
7. The Router
8. The Controller
9. The View
10. Templates
11. Sod this, take me to the download
12. Conclusion
13. Credits

Abstract

Model View Controller.

This tutorial will take you from the beginning to the end of building a MVC framework. The object is not soley to produce the finished MVC framework, although that will happen, but to demonstrate how MVC works and some of the concepts that lay behind it..
What is MVC?

MVC is a design pattern. A Design pattern is a code structure that allows for common coding frameworks to be replicated quickly. You might think of a design pattern as a skeleton or framework on which your application will be built.

In the MVC framework that is created in this tutorial, several key points will be raised. The first is the frameworks needs a single point of entry, ie: index.php. This is where all access to the site must be controlled from. To ensure that a single point of entry is maintained, htaccess can be utilized to ensure no other file may be accessed, and that we hide the index.php file in the url. Thus creating SEO and user friendly URL's.

It is beyond the scope of this tutorial to show how to set up htaccess and mod_rewrite and more information on these can be gained from the Apache manual. The .htaccess file itself looks like this.
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]

The .htaccess file will permit access to the site via urls such as
http://www.example.com/news/show

If you do not have mod_rewrite available, the entry to the site will be the same, except that the URL will contain the values needed such as:
http://www.example.com/index.php?rt=news/show
The Site Structure

In this tutorial several directories are required to hold the various components that make up the MVC framework. The index.php and the .htaccess files will, of course, reside at the top level. We will need a directory to hold the application code, and directories for the model view and controllers. The site structure should look like this:
html
application
controller
includes
model
views
.htaccess
index.php

The Index File

As previously mentioned, the index.php file is our single point of access. As such, it provides the ideal space for declaring variables and site wide configurations. It is in this file that we will also call a helper file to initialize a few values. This file will be called init.php and it will be placed in includes directory as shown in the direcory structure. The index file therefore, will begin like this:

<?php

/*** error reporting on ***/
error_reporting(E_ALL);

/*** define the site path constant ***/
$site_path = realpath(dirname(__FILE__));
define ('__SITE_PATH', $site_path);

/*** include the init.php file ***/
include 'includes/init.php';

?>

The index.php file so far only sets the error reporting, includes the init file, and defines the site path constant. With this file in place, and the .htaccess file we can begin to build the registry. In this MVC framework, the registry object is passed to other objects and contains site wide variables without the the use globals. To create a new registry object, we use the init.php file in the includes directory.

Of course, to create new object we need to include the registry class definition file. During the building of the MVC framework we will be including the application class files directly. Any PHP class definition files which are used by the model will be autoloaded as they can become quite cumbersome with larger applications. To alleviate some of this PHP has the __autoload function to help us out. After the application includes, the __autoload function will immediately follow to load class definition files automatically when they are required by the system. That is, when the new keyword is used. The class definitions will be stored in a directory called model. The includes/init.php file should now look like this.

<?php

/*** include the controller class ***/
include __SITE_PATH . '/application/' . 'controller_base.class.php';

/*** include the registry class ***/
include __SITE_PATH . '/application/' . 'registry.class.php';

/*** include the router class ***/
include __SITE_PATH . '/application/' . 'router.class.php';

/*** include the template class ***/
include __SITE_PATH . '/application/' . 'template.class.php';

/*** auto load model classes ***/
function __autoload($class_name) {
$filename = strtolower($class_name) . '.class.php';
$file = __SITE_PATH . '/model/' . $filename;

if (file_exists($file) == false)
{
return false;
}
include ($file);
}

/*** a new registry object ***/
$registry = new registry;

?>

Here is should be noted that the autoload function uses a naming convention for the class definition files to be included. They must all follow the convention of ending in .class.php and the class name must be that of the .class.php file name. So that to create a new "news" object the class definition file name must be news.class.php and the class must be named "news". With these files in place we are well on the way, however our MVC does not do anything yet. In fact, if you tried to access the index.php file now, you would get many errors about missing files. Mostly from the files in the application directory. So, lets begin by creating those files each can be blank or simply contain

<?php

?>

The files to create in the application directory are:

* controller_base.class.php
* registry.class.php
* router.class.php
* template.class.php

Note that although these files are not autoloaded, we have still maintained the same naming convention by calling the files .class.php
The Registry

The registry is an object where site wide variables can be stored without the use of globals. By passing the registry object to the controllers that need them, we avoid pollution of the global namespace and render our variables safe. We need to be able to set registry variables and to get them. The php magic functions __set() and __get() are ideal for this purpose. So, open up the registry.class.php in the applications directory and put the following code in it:

<?php

Class Registry {

/*
* @the vars array
* @access private
*/
private $vars = array();


/**
*
* @set undefined vars
*
* @param string $index
*
* @param mixed $value
*
* @return void
*
*/
public function __set($index, $value)
{
$this->vars[$index] = $value;
}

/**
*
* @get variables
*
* @param mixed $index
*
* @return mixed
*
*/
public function __get($index)
{
return $this->vars[$index];
}

}

?>

With the registry in place, our system is working. It does not do anything or display anything, but we have a functional system. The __set() and __get() magic function now allow us to set variables within the registry and store them there. Now to add the Model and router classes.
The Model

The Model is the "M" in MVC. The model is where business logic is stored. Business logic is loosely defined as database connections or connections to data sources, and provides the data to the controller. As I am a fan of CAV (Controller Action View) we will blur the line between the Model and Controller. This is not strictly how MVC should work, but this is PHP baby. Our database connection is a simple singleton design pattern and resides in the classes directory and can be called statically from the controller and set in the registry. Add this code to the init.php file we created earlier.

<?php

/*** create the database registry object ***/
$registry->db = db::getInstance();

?>

Like all registry members, the database is now globally availabe to our scripts. As the class is a singleton we always get the same instance back. Now that registry objects can be created a method of controlling what is loaded is needed.
The Router

The router class is responsible for loading up the correct controller. It does nothing else. The value of the controller comes from the URL. The url will look a like this:
http://www.example.com/index.php?rt=news
or if you have htaccess amd mod_rewrite working like this:
http://www.example.com/news

As you can see, the route is the rt variable with the value of news. To begin the router class a few things need to be set. Now add this code to the router.class.php file in the application directory.


<?php

class router {
/*
* @the registry
*/
private $registry;

/*
* @the controller path
*/
private $path;

private $args = array();

public $file;

public $controller;

public $action;

function __construct($registry) {
$this->registry = $registry;
}

So it does not look like much yet but is enough to get us started. We can load the router into the registry also. Add this code to the index.php file.

/*** load the router ***/
$registry->router = new router($registry);

Now that the router class can be loaded, we can continue with the router class by adding a method to set the controller directory path. Add this block of code to the router.class.php file.

<?php
/**
*
* @set controller directory path
*
* @param string $path
*
* @return void
*
*/
function setPath($path) {

/*** check if path i sa directory ***/
if (is_dir($path) == false)
{
throw new Exception ('Invalid controller path: `' . $path . '`');
}
/*** set the path ***/
$this->path = $path;
}

And to set the controller path in the registry is a simple matter of adding this line to the index.php file

/*** set the path to the controllers directory ***/
$router->setPath (__SITE_PATH . 'controller');

With the controller path set we can load the controller. We will create a method to called loader() to get the controller and load it. This method will call a getController() method that will decide which controller to load. If a controller is not found then it will default back to the index. The loader method looks like this.

<?php

/**
*
* @load the controller
*
* @access public
*
* @return void
*
*/
public function loader()
{
/*** check the route ***/
$this->getController();

/*** if the file is not there diaf ***/
if (is_readable($this->file) == false)
{
echo $this->file;
die ('404 Not Found');
}

/*** include the controller ***/
include $this->file;

/*** a new controller class instance ***/
$class = $this->controller . 'Controller_';
$controller = new $class($this->registry);

/*** check if the action is callable ***/
if (is_callable(array($controller, $this->action)) == false)
{
$action = 'index';
}
else
{
$action = $this->action;
}
/*** run the action ***/
$controller->$action();
}

The getController method that the loader() method calls does the work. By taking the route variables from the url via $_GET['rt'] it is able to check if a contoller was loaded, and if not default to index. It also checks if an action was loaded. An action is a method within the specified controller. If no action has been declared, it defaults to index. Add the getController method to the router.class.php file.

<?php
/**
*
* @get the controller
*
* @access private
*
* @return void
*
*/
private function getController() {

/*** get the route from the url ***/
$route = (empty($_GET['rt'])) ? '' : $_GET['rt'];

if (empty($route))
{
$route = 'index';
}
else
{
/*** get the parts of the route ***/
$parts = explode('/', $route);
$this->controller = $parts[0];
if(isset( $parts[1]))
{
$this->action = $parts[1];
}
}

if (empty($this->controller))
{
$this->controller = 'index';
}

/*** Get action ***/
if (empty($this->action))
{
$this->action = 'index';
}

/*** set the file path ***/
$this->file = $this->path .'/'. $this->controller . '.php';
}
?>
The Controller

The Contoller is the C in MVC. The base controller is a simple abstract class that defines the structure of all controllers. By including the registry here, the registry is available to all class that extend from the base controller. An index() method has also been included in the base controller which means all controller classes that extend from it must have an index() method themselves. Add this code to the controller.class.php file in the application directory.

<?php

Abstract Class baseController {

/*
* @registry object
*/
protected $registry;

function __construct($registry) {
$this->registry = $registry;
}

/**
* @all controllers must contain an index method
*/
abstract function index();
}

?>

Whilst we are in the controller creating mood, we can create an index controller and a blog controller. The index controller is the sytem default and it is from here that the first page is loaded. The blog controller is for an imaginary blog module. When the blog module is specified in the URL
http://www.example.com/blog
then the index method in the blog controller is called. A view method will also be created in the blog controller and when specified in the URL
http://www.example.com/blog/view
then the view method in the blog controller will be loaded. First lets see the index controller. This will reside in the controller directory.

<?php

class indexController extends baseController {

public function index() {
/*** set a template variable ***/
$this->registry->template->welcome = 'Welcome to PHPRO MVC';

/*** load the index template ***/
$this->registry->template->show('index');
}

}

?>

The indexController class above shows that the indexController extends the baseController class, thereby making the registry available to it without the need for global variables. The indexController class also contains the mandatory index() method that ll controllers must have. Within itn index() method a variable named "welcome" is set in the registry. This variable is available to the template when it is loaded via the template->show() method.

The blogController class follows the same format but has has one small addition, a view() method. The view() method is an example of how a method other than the index() method may be called. The view method is loaded via the URL
http://www.example.com/blog/view

<?php

Class blogController Extends baseController {

public function index() {
$this->registry->template->blog_heading = 'This is the blog Index';
$this->registry->template->show('blog_index');
}


public function view(){

/*** should not have to call this here.... FIX ME ***/

$this->registry->template->blog_heading = 'This is the blog heading';
$this->registry->template->blog_content = 'This is the blog content';
$this->registry->template->show('blog_view');
}

}
?>
The View

The View, as you might have guessed, is the V in MVC. The View contains code that relates to presentation and presentation logic such as templating and caching. In the controller above we saw the show() method. This is the method that calls the view. The major component in the PHPRO MVC is the template class. The template.class.php file contains the class definition. Like the other classes, it has the registry available to it and also contains a __set() method in which template variables may be set and stored.

The show method is the engine room of the view. This is the method that loads up the template itself, and makes the template variables available. Some larger MVC's will implement a template language that adds a further layer of abstraction from PHP. Added layers mean added overhead. Here we stick with the speed of PHP within the template, yet all the logic stays outside. This makes it easy for HTML monkies to create websites without any need to learn PHP or a template language. The template.class.php file looks like this:

<?php

Class Template {

/*
* @the registry
* @access private
*/
private $registry;

/*
* @Variables array
* @access private
*/
private $vars = array();

/**
*
* @constructor
*
* @access public
*
* @return void
*
*/
function __construct($registry) {
$this->registry = $registry;

}


/**
*
* @set undefined vars
*
* @param string $index
*
* @param mixed $value
*
* @return void
*
*/
public function __set($index, $value)
{
$this->vars[$index] = $value;
}


function show($name) {
$path = __SITE_PATH . '/views' . '/' . $name . '.php';

if (file_exists($path) == false)
{
throw new Exception('Template not found in '. $path);
return false;
}

// Load variables
foreach ($this->vars as $key => $value)
{
$$key = $value;
}

include ($path);
}


}

?>
Templates

The templates themselves are basically HTML files with a little PHP embedded. Do not let the separation Nazi's try to tell you that you need to have full seperation of HTML and PHP. Remember, PHP is an embeddable scripting language. This is the sort of task it is designed for and makes an efficient templating language. The template files belong in the views directory. Here is the index.php file.

<h1><?php echo $welcome; ?></h1>

Well, that was pretty amazing.. Now for the blog_index.php file.

<h1><?php echo $blog_heading; ?></h1>

And finally the blog_view.php file..

<h1><?php echo $blog_heading; ?></h1>

<p><?php echo $blog_content; ?></p>

In the above template files note that the variable names in the templates, match the template variables created in the controller.

MVC in PHP

What is MVC?

This is a broad definition of the components as defined by the pattern. Later on I will describe variants of this but this is MVC as described by the original implementations in Smalltalk-80

The Model

In its simplest form the model stores data which is to be accessed by the view and written to by the controller.

The model is the most complex of all the parts of the system and will contain all the logic which is specific to the application and where domain entities which relate to real world concepts (such as "a user" or "an order") are stored. It is the part of the application which takes data (from any source) and processes it. The model also handles all data access and storage. It has no knowledge of any controllers or views which may use it.

For example, in PHP the model may represent a "User" in the system. It will handle any operations regarding users. Saving/loading records, validating registrations.

The model is not (common mistakes made by those misinterpreting the pattern):

  • A simple data access point
  • A class called "model" which represents a single database table

The View

The view contains all the display logic. In PHP it will be the part of the application which generates the HTML. It has direct access to the Model and can query the model to get its data. It can create callbacks to its controller (for example a clicking a button in the view would trigger an action in the controller).

The View is not (common mistakes made by those misinterpreting the pattern):

  • Absent of logic
  • Given data by the controller

The Controller

The controller takes user input and updates the model where required. Where there is no user interaction (e.g. where a static data set is displayed and will be the same every time), no controller should be necessary. It is important to note that the controller is not a mediator or gateway between the view and the model. The view gets its own data from its model. The controller accesses the model but does not contain any display logic itself. All the controller does is respond to user input.

Each controller is linked to a single view and a single model.

The Controller is not (common mistakes made by those misinterpreting the pattern):

  • A gateway/mediator between the model and the view
  • The place where views get initialised based on the state of a model. The controller is linked to a single view and responds to actions on it. For example a list of products would be a single view. The controller would handle user actions such as sorting the list, filtering the records it's displaying based on criteria specified by users. It would not also deal with displaying the info for a single product. This is a different view, which requires its own controller.

Program flow

The typical program flow in MVC is:

  • The model, view and controller are initialised
  • The view is displayed to the user, reading data from the model
  • The user interacts with the view (e.g. presses a button) which calls a specified controller action
  • The controller updates the model in some way
  • The view is refreshed (fetching the updated data from the model)

Hello World:

<?php

class Model {
public $text;

public function __construct() {
$this->text = 'Hello world!';
}
}


class Controller {
protected $model;

public function __construct(Model $model) {
$this->model = $model;
}
}


class View {
protected $model;
protected $controller;

public function __construct(Controller $controller, Model $model) {
$this->controller = $controller;
$this->model = $model;
}

public function output() {
return $this->model->text;
}

}

//initiate the triad
$model = new Model();
//It is important that the controller and the view share the model
$controller = new Controller($model);
$view = new View($controller, $model);
echo $view->output();
?>


Example 2 :


<?php
class Model {
public $text;

public function __construct() {
$this->text = 'Hello world!';
}
}

class View {
protected $model;
protected $controller;

public function __construct(Controller $controller, Model $model) {
$this->controller = $controller;
$this->model = $model;
}

public function output() {
return '' . $this->model->text . '';
}

}

class Controller {
protected $model;

public function __construct(Model $model) {
$this->model = $model;
}

public function textClicked() {
$this->model->text = 'Text Updated';
}
}


$model = new Model();
//It is important that the controller and the view share the model
$controller = new Controller($model);
$view = new View($controller, $model);
if (isset($_GET['action'])) $controller->{$_GET['action']}();
echo $view->output();
?>