基于PSR-0编码规范开发一套PHP-MVC框架(一)

一、入口文件。index.php

<?php
header('Content-type:text/html;charset=utf-8');
date_default_timezone_set('PRC');
require_once(__DIR__.'/configs/Website.php');
require_once(__DIR__.'/frame/Common/Function.php');
require_once(__DIR__.'/frame/App.php');
spl_autoload_register('frame\App::autoload');
frame\App::run();
?>

二、站点全局配置文件。configs/Website.php

<?php
define('BASEPATH',dirname(dirname(__FILE__)));
define('APP',BASEPATH.'/app');
define('CTRL',BASEPATH.'/app/Controllers');
define('CTRLNAMESPACE','app\Controllers\\');
define('DEBUG',TRUE);

三、全局路由配置文件。configs/Routes.php

<?php
/*
*    路由结构
*    array(
*       '命名空间'=>array(
*           '路由别名'=>'控制器@方法'
*       )
*   )
*/
return array(

    'Home'=>array(
        'index-index'=>'IndexController@index',
        'index/test'=>'IndexController@test',
    ),

    'Admin'=>array(
        'login'=>'IndexController@login'
    ),
    
);

四、框架启动文件。frame/App.php

<?php
namespace frame;
use frame\Libs\Route;

class App
{
    //加载控制器文件执行方法
    static public function run()
    {
        $route = new Route();
        $ctrl = $route->ctrl;
        $action = $route->action;
        $namespace = $route->namespace;
        if($namespace) {
            $ctrlFile = CTRL.'/'.$namespace.'/'.$ctrl.'.php' ;
            $ctrlObj = CTRLNAMESPACE.$namespace.'\\'.$ctrl;
        } else {
            $ctrlFile = CTRL.'/'.$ctrl.'Controller.php';
            $ctrlObj =  CTRLNAMESPACE.$ctrl.'Controller' ;
        }
        if(is_file($ctrlFile)) {
            require_once($ctrlFile);
            $obj = new $ctrlObj;
            if(method_exists($obj,$action)) {
                $obj->$action();
            } else {
                throw new \Exception($action."方法不存在", 1);
                
            }
        } else {
            throw new \Exception($ctrl."控制器不存在", 1);
        }
    }
    
    //自动加载类文件
    static public function autoload($class)
    {
        $file = BASEPATH.'/'.str_replace('\\', '/', $class).'.php';
        if(is_file($file)) {
            require_once($file);
        } else {
            return false;
        }
    }
}

五、加载配置类。frame/Libs/Config.php

<?php
namespace frame\Libs;
class Config
{
    static $configs = [];
    /*
    *    $file : 文件名
    *    $name : 键名
    *    $flag : 获取全部选项
    */
    static public function get($file,$name,$flag = false)
    {
        if(isset(self::$configs[$file])) {
            return $flag ? self::$configs[$file] : self::$configs[$file][$name];
        } else {
            $filename = BASEPATH.'/configs/'.ucfirst($file).'.php';
            if(is_file($filename)) {
                $config = require_once($filename);
                $flag ? self::$configs[$file] = $config : self::$configs[$file] = $config[$name];
                return $flag ? $config : $config[$name];
            } else {
                throw new \Exception($filename."配置文件不存在", 1);
            }
        }
    }
}

六、路由类。frame/Libs/Route.php

<?php
namespace frame\Libs;
use frame\Libs\Config;

class Route
{
    public $ctrl;
    public $action;
    public $namespace;

    public function __construct()
    {
        $uri = $_SERVER['REQUEST_URI'];
        if(isset($uri) && $uri != '/') {
            $path = explode('?', trim($uri,'/'));
            $isExists = $this->checkRoute($path[0]);
            if(!isset($path[0]) || !$isExists) {
                throw new \Exception($path[0]."路由不存在", 1);            
            }
        } else {
            $this->ctrl = 'Welcome';
            $this->action = 'index';
        }
    }

    private function checkRoute($alias)
    {
        $routes = Config::get('Routes',null,true);
        foreach ($routes as $key => $value) {

            foreach ($value as $k => $v) {
                if($k == $alias) {
                    $c = explode('@', $v);
                    $this->ctrl = $c[0];
                    $this->action = $c[1];
                    $this->namespace = $key;
                    return true;
                } 
            }
        }
        return false;
    }
}

七、默认控制器。app/Controllers/WelcomeController.php

<?php
namespace app\Controllers;
class WelcomeController
{
    public function index()
    {
        echo ("<h1>Hello,World</h1>欢迎使用PHP-FRAME框架");
    }
}

八、隐藏index.php文件。.htaccess

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

九、本地域名访问 http://localhost
《基于PSR-0编码规范开发一套PHP-MVC框架(一)》

    原文作者:骆驼祥子
    原文地址: https://segmentfault.com/a/1190000014411637
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞