Ví dụ mô hình MVC và ngôn ngữ PHP
Cấu trúc thư mục của ví dụ
Trong thư mục project demo có 3 thư mục nhỏ đó là model, controller và view (hiện thực hóa của mô hình MVC). File index.php chứa giao diện form tương tác với người dùng.
Giao diện người dùng
Giao diện của form tương tác với người dùng
Kết quả khi chương trình thực hiện phép tính
Nội dung mã nguồn demo
File PROJ_1/index.php
<html> <head> <title>Calculation using MVC Model</title> <style type="text/css"> *{color:#279} #form{ width:300px; padding:20px; border:4px solid #279; } #form h2{ font-size:35px; margin:0; } #form p{ font-size:15px; color:#222222; } </style> </head> <body> <form id="form" action="controller/CalcController.php" method="post"> <h2>Calculation using MVC Model</h2> <table> <tr> <td>NUMBER 1</td> <td><input type='text' name='number1'/></td> </tr> <tr> <td>NUMBER 2</td> <td><input type='text' name='number2'/></td> </tr> <tr> <td>METHOD</td> <td> <select name="method_v"> <option value="add">Add</option> <option value="sub">Sub</option> </select> </td> </tr> <tr> <td></td> <td><input type="submit" value="Send" name="btnSubmit"/></td> </tr> </table> </form> </body> </html>
File PROJ_1/controller/CalcModel.php
<?php class CalcModel { public $result; public $a; public $b; public function method_calc($method) { switch ($method) { case 'add': $this->result = $this->a + $this->b; break; case 'sub': $this->result = $this->a - $this->b; break; default: $this->result = "No support"; break; } } } ?>
File PROJ_1/controller/CalcController.php
<?php include_once('../model/CalcModel.php'); if(isset($_POST) && isset($_POST['btnSubmit'])) { $var1 = $_POST['number1']; $var2 = $_POST['number2']; $method = $_POST['method_v']; $calc = new CalcModel(); $calc->a = $var1; $calc->b = $var2; $calc->method_calc($method); } include_once('../view/CalcView.php'); ?>
File PROJ_1/view/CalcView.php
<html> <head> <title>Calculation using MVC Model</title> <style type="text/css"> .box{ width:300px; padding:20px; border:4px solid #279; } </style> </head> <body> <div class="box"> <h2>Calculation using MVC Model</h2> <p>Result: <?php echo $calc->result; ?></p> </div> </body> </html>