最新消息:自律使人变得更强大

学习编写PHP框架第一天-入口文件与核心类

admin 1218 次 0 条

准备一些需要用到的扩展

{
    "name":"PHPONE",
    "description":"PHP Framework",
    "author":"WRC",

    "require":{
        "php":">= 5.3.0",
        "filp/whoops":"*",  //debug
        "symfony/var-dumper":"*", //美化打印输出
        "catfan/medoo":"*", //数据库操作类
        "twig/twig":"*" //日志类
    },

    "repositories": {
    "packagist": {
            "type": "composer",
            "url": "https://packagist.phpcomposer.com"  //更换为第三方源
        }
    }
}

入口文件的定义

<?php

define('PHPONE',realpath('./'));  //框架目录
define('CORE',PHPONE.'/core');    //核心目录
define('APP',PHPONE.'/app');    //项目目录
define('MODEL','app');
define('DEBUG',true);
include "vendor/autoload.php";

if(DEBUG){
    $whoops = new \Whoops\Run;
    $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
    $whoops->register();
    ini_set('display_error','On');
}else{
    ini_set('display_error','Off');
}

include CORE.'/common/function.php';
include CORE.'/phpone.php';

spl_autoload_register('\core\phpone::load');
\core\phpone::run();

在core文件夹下建立一个phpone.php的核心类文件

<?php
namespace core;
use core\lib\log;
use core\lib\route;
class phpone{

    public static $classMap = [];
    public $assign;

    static public function run(){
        log::init();
        $route = new route;
        $controller = $route->controller;
        $action = $route->action;
        $controller_file = APP.'/controller/'.$controller.'Controller.php';
        $ctrlClass = '\\'.MODEL.'\controller\\'.$controller.'Controller';

        if(is_file($controller_file)){
            include $controller_file;
            $ctrl = new $ctrlClass;
            $ctrl->$action();
            log::log('controller:'.$controller.'  '.'action:'.$action);  //记录日志
        }else{
            throw new \Exception("控制器不存在".$controller_file);
        }

    }


    static public function load($class){
        if(isset($classMap[$class])){
            return true;
        }else{
            $class = str_replace('\\', '/', $class);
            $file  = PHPONE . '/' .$class . '.php';
            if(is_file($file)){
                include $file;
                self::$classMap[$class] = $class;
            }else{
                return false;
            }
        }
    }

    public function assign($name,$value){
        $this->assign[$name] = $value;
    }

    public function view($file){
        $file = APP.'/view'.$file;
        if(is_file($file)){
            extract($this->assign);  //该函数使用数组键名作为变量名,使用数组键值作为变量值
            include $file;
        }
    }
}
发表我的评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址