Simple PHP MVC Framework Example

https://www.phpflow.com/php/simple-mvc-architecture-example-in-php/

Simple PHP MVC Framework Example

Last Updated On: June 24, 2017| By: Parvez

Today we will discuss how to create MVC sample application in PHP.Because now days in php everybody creating class based structure of application and main problem in class based the all the things is in same function(such as view,model and action).So with help of MVC we will separate all layer. The MVC stands for Model,view and controller.You can get more information of MVC introduction from Model,View and Controller in MVC

Checkout other Tutorials,

The File Structure Of MVC Application Are Below:

Step 1: First we will create index.php file,In index file we will get the action from URL.

12345

<div id="container"> <ul> <li><a class="menu" href="PageController.php?action=userInfo">Domain1</a></li> </ul></div>

in above code we have created a link domain1, when we click the domain it will go controller file and action method.

Step 2: We will create base controller file.This file contains all methods which we will use in all controllers, in other words all common controller methods.

123456

<?phpabstract Class BaseController { public function render($file) { include '../' . $file .'.php';}?>

Step 3: Now we will create our module controller and extend base controller.

1234567891011121314

$obj = new Controller(); switch($_REQUEST['action']) { case 'userInfo' : $obj->getUserInfo(); break; }Class PageController Extends BaseController { public function getUserInfo() { $this->render('userinfo'); }}

Step 4: Now i am creating base_model class.This class contains all method which is common in all module model class.

1234

abstract Class Model { protected function insertData($table) { }}

Step 5: Lets create our module model file which will extend base model class.

12345678910111213141516171819202122

Class Page Extends Model { public function saveData() { switch($_REQUEST['method']) { case 'pageData' : $this->savePageData(); break; case 'default' : return 'No action'; break; } } protected function savePageData() { try { //write your logic } } catch (Exception $e) { return $e->getMessage(); } }

Step 6: How to call model method in controller file.

1234

public function saveData() { $result = $this->model->saveData(); }

Step 7: Created a new config.php file which will contain configuration level variable. Step 8: Created a new common_function.php file.This file contains all helper method which is available in all modules. Step 9: Finally we will create view file in view folder.This file contains HTML and js related functionality.

Last updated