PHP MVC Example

Posted on January 18, 2022
PHP

Here is an example of a basic Model-View-Controller (MVC) implementation in PHP:

Model:

class UserModel {
    private $name;
    private $email;

    public function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
    }

    public function getName() {
        return $this->name;
    }

    public function getEmail() {
        return $this->email;
    }
}
 

View:

class UserView {
    public function render($user) {
        echo "Name: " . $user->getName() . "<br>";
        echo "Email: " . $user->getEmail();
    }
}

Controller:

class UserController {
    private $model;
    private $view;

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

    public function updateName($name) {
        $this->model->name = $name;
    }

    public function updateEmail($email) {
        $this->model->email = $email;
    }

    public function renderView() {
        $this->view->render($this->model);
    }
}

Example of usage:

$userModel = new UserModel("Bhaktaraz Bhatta", "[email protected]");
$userView = new UserView();
$userController = new UserController($userModel, $userView);
$userController->renderView();
 

This will output:

Name: Bhaktaraz Bhatta
Email: [email protected]

This is a very basic example of how the MVC pattern can be implemented in PHP. There are many variations and frameworks that can be used to structure a PHP application using the MVC pattern.