Tuesday, August 16, 2011

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();
?>

Saturday, August 13, 2011

SOAP - simple Object Access Protocol

SOAP , NuSOAP and WSDL - Web Service Description Language(Web Service Definition Language):


What is SOAP?

SOAP is a standardized means of transferring data between two machines in a client-server configuration. SOAP is a W3C standardized (W3C, 2004) means of communicating with a web service across a network (local or Internet).

“SOAP is an XML-based messaging protocol.” (SoapUser.com, 2009)

SOAP messages (envelopes) are formed in XML, itself an open W3C standard. The client must haves an XML parser to interpret the document. XML is platform and programming language independent so it can be used by a wide range of computer systems. As SOAP is just a standard and not a process, it is not limited to any particular protocol (although HTTP is commonplace).

“WSDL is a document written in XML. The document describes a Web service. It specifies the location of the service and the operations (or methods) the service exposes.”(w3schools, 2009)

WSDL (Web Service Description Language) defines the web service and available methods to the client. This applies to all clients no matter from what context they are consuming the application.

The WSDL document also defines the following:

* The methods arguments
* The arguments data types
* Return value data type
* Port and binding data.

Example structure of a WSDL document: (w3schools, 2009)


<definitions>

<types>
definition of types........
</types>

<message>
definition of a message....
</message>

<portType>
definition of a port.......
</portType>

<binding>
definition of a binding....
</binding>

</definitions>

WSDL documents are very important to web services (and SOAP) because it is effectively a protocol that defines in very clear detail how the client will interact with it. A WSDL document also eliminates guess work and long laborious documentation. WSDL language is not easily readable by humans (despite being written in XML), especially when they get long. There are now several implementations of SOAP that ease the process and enable rapid application development. One example of this is NuSOAP.
What is NuSOAP?

“…the most viable PHP implementation of SOAP seems to be Dietrich Ayala’s SOAPx4, also known as NuSOAP” (Apple Inc, 09)

NuSOAP is a collection of classes that allows for rapid development of SOAP enabled PHP web services. NuSOAP is not a technology in itself, in the sense that it does not require any reconfiguration on the server, but rather acts as a middle man to ease the application development process.

Hello, World! Example [Server] (Nichol, 2004)


<?php

// Pull in the NuSOAP code

require_once('nusoap.php');

// Create the server instance

$server = new soap_server;

// Register the method to expose

$server->register('hello');

// Define the method as a PHP function

function hello($name) {

return 'Hello, ' . $name;

}

// Use the request to (try to) invoke the service

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';

$server->service($HTTP_RAW_POST_DATA);

?>

The above example demonstrates a NuSOAP server with one method that returns the same value that was passed to it (as a string).

Walkthrough:

* Reference the NuSOAP implementation
* Create a new instance of the server object, and name it.
* Register the method “hello” with the server object.
* Write the corresponding method and make it do “something”. (In this case, return the same string that was originally passed to it).
* If [when] there is post data, pass it to the server object and do something with it.

The code above is as basic as a NuSOAP example gets, but it shows clearly the steps required to start making use of SOAP without having to write (or even fully understand) the implementation yourself.

Hello, World! Example [Client] (Nichol, 2004)


<?php

// Pull in the NuSOAP code

require_once('nusoap.php');

// Create the client instance

$client = new soapclient('http://localhost/phphack/helloworld.php');

// Call the SOAP method

$result = $client->call('hello', array('name' => 'Scott'));

// Display the result

print_r($result);

?>

The client code is similar by design. Even though this example uses only PHP, it is possible to access the server using virtually any other language.

Walkthrough:

* Reference the NuSOAP implementation
* Create an instance of the SOAPClient and specify the remote path of the web service.
* Call the desired method and pass an argument (called ‘name’).
* The web service responds (if request is valid) and prints the result to the screen.

The disadvantage of using third party implementations is that debugging and error handling is more difficult, as you have no knowledge of the underlying code.