making own mvc framework in php

include these two classes will make

Request Class :

<?php

Class Request {

    private $_controller;
    private $_method;
    private $_args;

    public function __construct(){
        $str=$_SERVER['REQUEST_URI'];
       // echo "<pre>";
        //print_r($_SERVER);
        $first_slash = strpos($str, '/');
        $second_slash = strpos($str, '/', $first_slash+1);
        $str = substr($str, $second_slash+1);
        $parts = explode('/',$str);

        //print_r($parts);
        $this->_controller = ($c = array_shift($parts))? $c: 'index';
        $this->_method = ($c = array_shift($parts))? $c: 'index';
        $this->_args = (isset($parts[0])) ? $parts : array();
    }

    public function getController(){

        return $this->_controller;

    }
    public function getMethod(){

        return $this->_method;

    }
    public function getArgs(){

        return $this->_args;
    }
}

Router Class :

Class Router{

    public static function route(Request $request){

        $controller = $request->getController().'Controller';

        $method = $request->getMethod();

        $args = $request->getArgs();

        $controllerFile = dirname(__FILE__).'/controllers/'.$controller.'.php';
        if(is_readable($controllerFile)){
            require_once $controllerFile;

            $controller = new $controller;

            if(!empty($args)){
                call_user_func_array(array($controller,$method),$args);
            }else{
                call_user_func(array($controller,$method));
            }
            return;
        }

        throw new Exception('404 - '.$request->getController().'--Controller not found');
    }
}

Call them in index.php  like this :

$request=new Request();
        Router::route($request);

Creat controllers folder and first folder :

Class indexController {

    public function index() {
     // echo "index controoler callexd";
        include "views/auth/loginform.php";
    }

 

.htaccess in root :

RewriteEngine on

RewriteRule .*        index.php
Advertisements

About rahul23134654

Hi, I am Rahul Meha , B.E. in (I.T.)
This entry was posted in PHP. Bookmark the permalink.

One Response to making own mvc framework in php

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s