Monday 24 April 2017

MVC IN PHP


By
Nikhil,




MVC was originally designed for personal computing, it has been adapted and is widely used by web developers due to its emphasis on separation of concerns, and thus indirectly, reusable code. The pattern encourages the development of modular systems, allowing developers to quickly update, add, or even remove functionality.
First we crate the model:
<?php
class Modelex
{
    public $str;
    public fun__constex()
    {
        $this->str = "We got mvc with php!!";
    }
}
Npw we will create the view for model:
<?php
class Viewex
{
    private $mod;
    private $contr;
    public func__constex($contr,$mod)
    {
        $this->contr = $contr;
        $this->mod = $mod;
    }
    public func_optex()
    {
        return "<p>" . $this->mod->string . "</p>";
    }
}
Now we will create a controller for view and model:
<?php
class Contrex
{
    private $mod;
    public fun__const($mod)
    {
        $this->mod = $mod;
    }
}
We have our project started with some very basic classes for each part of the pattern. Now we need to set up the relationships between them:
<?php
$model = new Modex();
$controller = new Contrex($mod);
$view = new Viewex($contr, $mod);
echo $view->opt();
As you can see in the example above, we don’t have any Controller-specific functionality because we don’t have any user interactions defined with our application. The View holds all of the functionality as the example is purely for display purposes.
Let’s now expand the example to show how we would add functionality to the controller, thereby adding interactivity to the application:
<?php
class Modelex1
{
    public $string;
    public fun__construct1()
    {
        $this->string = “MVC + PHP = Awesome, click here!”;
    }
}
<?php
class Viewex
{
    private $model;
    private $controller;
    public fun__construct1($contr,$mod)
    {
        $this->controller = $contr;
        $this->model = $mod;
    }
    public function output()
    {
        return '<p><a href="mvc.php?action=clicked"' . $this->model->string . "</a></p>";
    }
}
<?php
class Controllerex
{
    private $mod;
    public fun__construct1($mod)
    {
        $this->model = $mod;
    }
    public function clicked()
    {
        $this->model->string = “Updated Data, thanks to MVC and PHP!”
    }
}
We’ve enhanced the application with some basic functionality. Setting up the relationship between our components now looks like this:
<?php
$model = new Modelex();
$controller = new Controllerex($mod);
$view = new Viewex($contr, $mod);
if (isset($_GET['action']) && !empty($_GET['action']))
{
    $controller->{$_GET['action']}();
}
echo $view->output();

No comments:

Post a Comment