首页 理论 架构 工程 规划 文档 白皮书 著作 研究 规范 下载 博客 关于 联系 开始使用 →

第六十四章 核心程序实现

第六十四章 核心程序实现

根据前述架构设计,逐步实现框架启动程序、核心管理类、自动加载程序、配置管理程序、路由程序和应用调度程序。通过完整代码说明核心程序之间的依赖关系和实际调用过程。

64.1 核心程序实现目标

核心程序是 WangStruct Framework 的运行基础,负责组织框架启动、类加载、配置读取、请求接收、路由解析、控制器调用和应用调度。

第六十二章建立了基础项目,第六十三章建立了安装与配置机制。本章将这些基础程序进一步组织为相互协作的核心运行系统。

本章实现以下六个部分:

  1. 框架启动程序:负责项目启动和运行入口组织。

  2. 核心管理类:负责框架初始化和核心对象协调。

  3. 自动加载程序:负责类文件定位和加载。

  4. 配置管理程序:负责配置读取、查询和管理。

  5. 路由程序:负责请求地址与控制器操作之间的映射。

  6. 应用调度程序:负责根据路由结果调用应用控制器并返回执行结果。

本章的实现重点是建立一条实际可调用的程序链:

\[ 启动入口 \rightarrow 自动加载 \rightarrow 核心初始化 \rightarrow 配置加载 \rightarrow 请求处理 \rightarrow 路由解析 \rightarrow 应用调度 \rightarrow 控制器执行 \rightarrow 响应输出 \]

需要注意:本章的核心程序是框架基础运行机制,不负责实现动态结构、知识、能力、认知、决策和智能运行等专业组件。这些组件在后续运行过程中由统一核心机制组织调用。

64.2 核心程序总体架构

核心程序采用分层组织方式,将框架启动、基础管理、HTTP处理和应用调度分开。

64.2.1 核心程序组成

程序 主要职责
Application 框架应用初始化与运行协调
Kernel 核心程序统一管理
Autoloader 类自动加载
Config 配置数据管理
ConfigLoader 配置文件加载
Request HTTP请求数据管理
Response HTTP响应数据管理
Router 路由解析
RouteCollection 路由定义管理
Dispatcher 应用调度
ControllerResolver 控制器定位与创建
ExceptionHandler 运行异常处理

各程序之间通过明确的对象接口进行调用,避免将所有功能集中到一个入口文件中。

64.2.2 核心调用关系

其中:

  • Application 是应用初始化入口。

  • Kernel 是核心管理对象。

  • Config 管理已经加载的配置数据。

  • Router 根据请求信息确定调用目标。

  • Dispatcher 负责执行调度。

  • Response 负责组织最终输出。

64.3 核心目录结构

本章在前面章节已经建立的目录基础上,扩展核心程序文件。

WangStruct/                                          # WangStruct框架项目根目录
├── framework/                                       # 框架核心程序目录
│   ├── Core/                                        # 框架核心管理目录
│   │   ├── Application.php                          # 框架应用初始化与运行入口
│   │   ├── Kernel.php                               # 框架核心程序统一管理类
│   │   └── ExceptionHandler.php                     # 框架异常处理类
│   ├── Loader/                                      # 自动加载程序目录
│   │   └── Autoloader.php                           # 命名空间与类文件自动加载类
│   ├── Config/                                      # 配置管理程序目录
│   │   ├── Config.php                               # 配置数据管理类
│   │   └── ConfigLoader.php                         # 配置文件加载类
│   ├── Http/                                        # HTTP请求与响应程序目录
│   │   ├── Request.php                              # HTTP请求对象
│   │   └── Response.php                             # HTTP响应对象
│   ├── Routing/                                     # 路由管理程序目录
│   │   ├── Router.php                               # 路由解析与匹配类
│   │   └── RouteCollection.php                      # 路由定义集合管理类
│   └── Application/                                 # 应用调度程序目录
│       ├── Dispatcher.php                           # 应用请求调度类
│       └── ControllerResolver.php                   # 控制器定位与创建类
├── app/                                             # 应用程序目录
│   ├── Controller/                                  # 应用控制器目录
│   │   └── IndexController.php                      # 默认首页控制器
│   └── routes.php                                   # 应用路由定义文件
├── config/                                          # 配置文件目录
│   ├── framework.php                                # 框架基础配置文件
│   ├── application.php                              # 应用配置文件
│   ├── environment.php                              # 运行环境配置文件
│   └── database.php                                 # 数据库连接配置文件
├── storage/                                         # 运行数据存储目录
│   ├── logs/                                        # 运行日志目录
│   ├── cache/                                       # 缓存数据目录
│   └── installation/                                # 安装状态目录
│       └── status.json                              # 框架安装状态文件
├── public/                                          # Web公共访问目录
│   └── index.php                                    # 框架统一启动入口
└── tests/                                           # 核心程序测试目录
    └── CoreTest.php                                 # 核心启动与调度测试程序

本章复用前面章节的配置、请求响应和路由设计方向,但为了形成完整调用过程,将相关基础接口在本章中明确实现。

目录中的文件应当按照上述职责建立,不应在实现过程中把路由解析、配置管理和控制器执行混写在一个程序中。

64.4 自动加载程序实现

自动加载程序负责根据命名空间找到类文件,使框架各组件能够按照统一规则组织和调用。

第八章已经介绍自动加载与类管理机制,第六十二章也建立了基础自动加载示例。本章将其整理为框架核心实际使用的版本。

64.4.1 Autoloader类

文件:

framework/Loader/Autoloader.php

<?php

namespace WangStruct\Loader;

class Autoloader
{
    protected $prefixes = array();

    public function addNamespace($prefix, $directory)
    {
        $prefix = trim($prefix, '\\') . '\\';

        $directory = rtrim(
            $directory,
            '/\\'
        ) . DIRECTORY_SEPARATOR;

        if (!isset($this->prefixes[$prefix])) {
            $this->prefixes[$prefix] = array();
        }

        if (!in_array(
            $directory,
            $this->prefixes[$prefix],
            true
        )) {
            $this->prefixes[$prefix][] = $directory;
        }

        return $this;
    }

    public function register()
    {
        spl_autoload_register(
            array($this, 'loadClass')
        );

        return $this;
    }

    public function loadClass($class)
    {
        foreach ($this->prefixes as $prefix => $directories) {

            $length = strlen($prefix);

            if (strncmp($prefix, $class, $length) !== 0) {
                continue;
            }

            $relativeClass = substr(
                $class,
                $length
            );

            $relativePath = str_replace(
                '\\',
                DIRECTORY_SEPARATOR,
                $relativeClass
            ) . '.php';

            foreach ($directories as $directory) {

                $file = $directory . $relativePath;

                if (is_file($file)) {
                    require_once $file;

                    return true;
                }
            }
        }

        return false;
    }
}

64.4.2 命名空间映射

框架命名空间与目录之间建立对应关系:

命名空间 目录
WangStruct\Core framework/Core
WangStruct\Loader framework/Loader
WangStruct\Config framework/Config
WangStruct\Http framework/Http
WangStruct\Routing framework/Routing
WangStruct\Application framework/Application
App\Controller app/Controller

例如:

WangStruct\Routing\Router

对应:

framework/Routing/Router.php

自动加载程序只负责类文件定位,不负责判断类的业务功能,也不负责实例化对象。

64.5 配置管理程序实现

配置管理程序负责加载配置文件、保存配置数据和提供统一读取接口。

第七章已经设计配置管理组件。本章实现核心运行所需要的基本接口,不重复扩展配置管理的全部高级功能。

64.5.1 Config类

文件:

framework/Config/Config.php

<?php

namespace WangStruct\Config;

class Config
{
    protected $items = array();

    public function set($key, $value)
    {
        $this->items[$key] = $value;

        return $this;
    }

    public function get($key, $default = null)
    {
        if (array_key_exists($key, $this->items)) {
            return $this->items[$key];
        }

        return $default;
    }

    public function has($key)
    {
        return array_key_exists($key, $this->items);
    }

    public function remove($key)
    {
        if (array_key_exists($key, $this->items)) {
            unset($this->items[$key]);
        }

        return $this;
    }

    public function all()
    {
        return $this->items;
    }
}

该类负责管理当前运行过程中的配置数据。

例如:

$config = new Config();

$config->set('debug', true);

$debug = $config->get('debug');

配置对象只负责保存和读取数据,不直接操作磁盘文件。

64.5.2 ConfigLoader类

文件:

framework/Config/ConfigLoader.php

<?php

namespace WangStruct\Config;

class ConfigLoader
{
    protected $config;

    protected $configPath;

    public function __construct(Config $config, $configPath)
    {
        $this->config = $config;

        $this->configPath = rtrim(
            $configPath,
            '/\\'
        );
    }

    public function load($fileName, $key = null)
    {
        if (basename($fileName) !== $fileName) {
            throw new \InvalidArgumentException(
                'Invalid configuration file name.'
            );
        }

        if (substr($fileName, -4) !== '.php') {
            $fileName .= '.php';
        }

        $file = $this->configPath
            . DIRECTORY_SEPARATOR
            . $fileName;

        if (!is_file($file)) {
            throw new \RuntimeException(
                'Configuration file not found: ' . $fileName
            );
        }

        $data = require $file;

        if (!is_array($data)) {
            throw new \RuntimeException(
                'Configuration file must return an array.'
            );
        }

        if ($key === null) {
            $key = pathinfo(
                $fileName,
                PATHINFO_FILENAME
            );
        }

        $this->config->set($key, $data);

        return $data;
    }

    public function loadAll($files)
    {
        foreach ($files as $fileName) {
            $this->load($fileName);
        }

        return $this->config;
    }
}

64.5.3 配置读取方式

例如:

$config = new Config();

$loader = new ConfigLoader(
    $config,
    ROOT_PATH . '/config'
);

$loader->loadAll(array(
    'framework.php',
    'application.php',
    'environment.php'
));

$framework = $config->get('framework');

$appName = $framework['name'];

此处使用配置名称作为顶层键。

例如:

$config->get('framework');

返回框架配置数组。

本章暂不实现复杂的多级点号访问、配置覆盖优先级、动态配置持久化和环境配置合并。这些属于第七章配置管理组件的进一步实现内容。

64.6 HTTP请求与响应程序

路由程序需要读取当前请求的 URL 和 HTTP 方法,应用调度程序则需要将控制器执行结果转换为 HTTP 响应。

因此,本章需要建立最小的请求对象和响应对象。

64.6.1 Request类

文件:

framework/Http/Request.php

<?php

namespace WangStruct\Http;

class Request
{
    protected $method;

    protected $uri;

    protected $query;

    protected $post;

    public function __construct()
    {
        $this->method = isset($_SERVER['REQUEST_METHOD'])
            ? strtoupper($_SERVER['REQUEST_METHOD'])
            : 'GET';

        $this->uri = isset($_SERVER['REQUEST_URI'])
            ? $_SERVER['REQUEST_URI']
            : '/';

        $this->query = $_GET;

        $this->post = $_POST;
    }

    public function getMethod()
    {
        return $this->method;
    }

    public function getUri()
    {
        $path = parse_url(
            $this->uri,
            PHP_URL_PATH
        );

        return $path ? $path : '/';
    }

    public function getQuery($key = null, $default = null)
    {
        if ($key === null) {
            return $this->query;
        }

        return isset($this->query[$key])
            ? $this->query[$key]
            : $default;
    }

    public function getPost($key = null, $default = null)
    {
        if ($key === null) {
            return $this->post;
        }

        return isset($this->post[$key])
            ? $this->post[$key]
            : $default;
    }
}

请求对象负责保存请求方法、URL路径和参数。

本章实现的是基础 GET、POST 请求读取接口。PUT、PATCH、DELETE 的请求体解析以及请求头、文件上传、JSON 请求解析等功能,仍需结合第九章请求与响应组件进一步完善。

64.6.2 Response类

文件:

framework/Http/Response.php

<?php

namespace WangStruct\Http;

class Response
{
    protected $content = '';

    protected $statusCode = 200;

    protected $headers = array();

    public function __construct($content = '', $statusCode = 200)
    {
        $this->content = $content;

        $this->statusCode = (int) $statusCode;

        $this->headers['Content-Type'] =
            'text/html; charset=utf-8';
    }

    public function setContent($content)
    {
        $this->content = $content;

        return $this;
    }

    public function setStatusCode($statusCode)
    {
        $this->statusCode = (int) $statusCode;

        return $this;
    }

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

        return $this;
    }

    public function send()
    {
        if (!headers_sent()) {

            http_response_code($this->statusCode);

            foreach ($this->headers as $name => $value) {
                header($name . ': ' . $value);
            }
        }

        echo $this->content;
    }
}

响应对象负责组织响应内容、状态码和响应头。

控制器不应直接承担 HTTP 响应头管理工作,而应将结果交给响应对象统一处理。

64.7 路由程序实现

路由程序负责将 HTTP 请求地址与应用控制器操作建立映射关系。

第十章已经设计路由管理组件。本章实现能够支持基础项目运行的路由集合、路由注册和路由匹配接口。

64.7.1 RouteCollection类

文件:

framework/Routing/RouteCollection.php

<?php

namespace WangStruct\Routing;

class RouteCollection
{
    protected $routes = array();

    public function add($method, $path, $controller, $action)
    {
        $method = strtoupper($method);

        $path = '/' . trim($path, '/');

        if ($path === '//') {
            $path = '/';
        }

        $this->routes[] = array(
            'method' => $method,
            'path' => $path,
            'controller' => $controller,
            'action' => $action
        );

        return $this;
    }

    public function getRoutes()
    {
        return $this->routes;
    }
}

路由集合负责保存路由定义,不直接处理 HTTP 请求。

例如:

$routes = new RouteCollection();

$routes->add(
    'GET',
    '/',
    'IndexController',
    'index'
);

表示 GET 请求访问 / 时调用 IndexController 的 index 方法。

64.7.2 Router类

文件:

framework/Routing/Router.php

<?php

namespace WangStruct\Routing;

use WangStruct\Http\Request;

class Router
{
    protected $routes;

    public function __construct(RouteCollection $routes)
    {
        $this->routes = $routes;
    }

    public function match(Request $request)
    {
        $method = $request->getMethod();

        $path = $request->getUri();

        foreach ($this->routes->getRoutes() as $route) {

            if ($route['method'] !== $method) {
                continue;
            }

            if ($route['path'] !== $path) {
                continue;
            }

            return $route;
        }

        return null;
    }
}

当前路由程序采用 HTTP 方法和完整路径精确匹配。

例如:

HTTP方法 请求路径 控制器 操作
GET / IndexController index
GET /about IndexController about
GET /products ProductController index

动态路由、路由参数、路由分组、路由命名和中间件等功能不在本章基础实现范围内,不能将当前精确匹配程序描述为已经具备这些能力。

64.8 控制器定位程序

路由匹配后,需要根据路由结果找到对应控制器类并创建对象。

控制器定位程序负责控制器类名解析、类存在检查和对象实例化。

64.8.1 ControllerResolver类

文件:

framework/Application/ControllerResolver.php

<?php

namespace WangStruct\Application;

class ControllerResolver
{
    protected $controllerNamespace;

    public function __construct($controllerNamespace)
    {
        $this->controllerNamespace = trim(
            $controllerNamespace,
            '\\'
        );
    }

    public function resolve($controllerName)
    {
        if (!preg_match(
            '/^[A-Za-z_][A-Za-z0-9_]*$/',
            $controllerName
        )) {
            throw new \InvalidArgumentException(
                'Invalid controller name.'
            );
        }

        $class = $this->controllerNamespace
            . '\\'
            . $controllerName;

        if (!class_exists($class)) {
            throw new \RuntimeException(
                'Controller class not found: ' . $class
            );
        }

        return new $class();
    }
}

该程序通过应用控制器命名空间和控制器名称确定类。

例如:

$resolver = new ControllerResolver(
    'App\Controller'
);

$controller = $resolver->resolve(
    'IndexController'
);

对应创建:

new \App\Controller\IndexController();

本章采用统一的应用控制器命名空间。不同模块的控制器命名空间和模块定位机制,需要后续在应用项目和模块管理机制中扩展。

64.9 应用调度程序实现

应用调度程序负责将路由匹配结果转换为实际控制器调用。

它是路由程序和应用控制器之间的协调层。

64.9.1 Dispatcher类

文件:

framework/Application/Dispatcher.php

<?php

namespace WangStruct\Application;

use WangStruct\Http\Request;
use WangStruct\Http\Response;
use WangStruct\Routing\Router;

class Dispatcher
{
    protected $router;

    protected $controllerResolver;

    public function __construct(
        Router $router,
        ControllerResolver $controllerResolver
    ) {
        $this->router = $router;

        $this->controllerResolver = $controllerResolver;
    }

    public function dispatch(Request $request)
    {
        $route = $this->router->match($request);

        if ($route === null) {
            return new Response(
                '404 Not Found',
                404
            );
        }

        $controller = $this->controllerResolver->resolve(
            $route['controller']
        );

        $action = $route['action'];

        if (!preg_match(
            '/^[A-Za-z_][A-Za-z0-9_]*$/',
            $action
        )) {
            throw new \InvalidArgumentException(
                'Invalid controller action.'
            );
        }

        if (!is_callable(array($controller, $action))) {
            throw new \RuntimeException(
                'Controller action not found.'
            );
        }

        $result = call_user_func(
            array($controller, $action),
            $request
        );

        if ($result instanceof Response) {
            return $result;
        }

        if (is_array($result) || is_object($result)) {

            return new Response(
                json_encode(
                    $result,
                    JSON_UNESCAPED_UNICODE
                ),
                200
            )->setHeader(
                'Content-Type',
                'application/json; charset=utf-8'
            );
        }

        return new Response(
            (string) $result,
            200
        );
    }
}

调度程序执行以下步骤:

  1. 调用路由程序匹配当前请求。

  2. 获取控制器名称和操作名称。

  3. 调用控制器定位程序创建对象。

  4. 检查控制器操作是否可调用。

  5. 执行控制器方法。

  6. 将执行结果转换为 Response 对象。

  7. 返回统一响应对象。

控制器方法可以返回字符串、数组、对象或 Response 对象。

本章采用简单的返回值约定。后续可以通过统一响应规范完善 JSON、HTML、文件下载和异常响应等处理方式。

64.10 核心管理类实现

前面已经建立自动加载、配置、请求响应、路由和应用调度程序。现在需要一个核心管理类组织这些程序之间的关系。

本章由 Kernel 负责协调核心程序。

64.10.1 Kernel类

文件:

framework/Core/Kernel.php

<?php

namespace WangStruct\Core;

use WangStruct\Config\Config;
use WangStruct\Config\ConfigLoader;
use WangStruct\Http\Request;
use WangStruct\Routing\RouteCollection;
use WangStruct\Routing\Router;
use WangStruct\Application\Dispatcher;
use WangStruct\Application\ControllerResolver;

class Kernel
{
    protected $rootPath;

    protected $config;

    protected $configLoader;

    protected $request;

    protected $router;

    protected $dispatcher;

    public function __construct($rootPath)
    {
        $this->rootPath = rtrim(
            $rootPath,
            '/\\'
        );
    }

    public function initialize()
    {
        $this->initializeConfig();

        $this->initializeRequest();

        $this->initializeRouting();

        $this->initializeDispatcher();

        return $this;
    }

    protected function initializeConfig()
    {
        $this->config = new Config();

        $this->configLoader = new ConfigLoader(
            $this->config,
            $this->rootPath . '/config'
        );

        $this->configLoader->loadAll(array(
            'framework.php',
            'application.php',
            'environment.php'
        ));
    }

    protected function initializeRequest()
    {
        $this->request = new Request();
    }

    protected function initializeRouting()
    {
        $routeFile = $this->rootPath . '/app/routes.php';

        if (!is_file($routeFile)) {
            throw new \RuntimeException(
                'Application route file not found.'
            );
        }

        $routes = require $routeFile;

        if (!$routes instanceof RouteCollection) {
            throw new \RuntimeException(
                'Route file must return RouteCollection.'
            );
        }

        $this->router = new Router($routes);
    }

    protected function initializeDispatcher()
    {
        $applicationConfig = $this->config->get(
            'application',
            array()
        );

        $namespace = isset($applicationConfig['controller_namespace'])
            ? $applicationConfig['controller_namespace']
            : 'App\\Controller';

        $resolver = new ControllerResolver($namespace);

        $this->dispatcher = new Dispatcher(
            $this->router,
            $resolver
        );
    }

    public function handle()
    {
        return $this->dispatcher->dispatch(
            $this->request
        );
    }

    public function getConfig()
    {
        return $this->config;
    }
}

核心管理类将各个程序组合起来,但没有把各个专业程序的内部实现复制到 Kernel 中。

64.10.2 Application类

文件:

framework/Core/Application.php

<?php

namespace WangStruct\Core;

class Application
{
    protected $rootPath;

    protected $kernel;

    public function __construct($rootPath)
    {
        $this->rootPath = rtrim(
            $rootPath,
            '/\\'
        );
    }

    public function initialize()
    {
        $this->kernel = new Kernel(
            $this->rootPath
        );

        $this->kernel->initialize();

        return $this;
    }

    public function run()
    {
        if (!$this->kernel) {
            throw new \RuntimeException(
                'Application has not been initialized.'
            );
        }

        $response = $this->kernel->handle();

        $response->send();

        return $response;
    }

    public function getKernel()
    {
        return $this->kernel;
    }
}

Application 负责对外提供框架启动和运行接口。

其基本调用方式:

$application = new Application(ROOT_PATH);

$application->initialize();

$application->run();

这样,项目入口不需要直接创建 Router、Dispatcher 和 ControllerResolver 等内部对象。

64.11 应用路由定义

应用路由由应用自身提供,框架核心负责加载和解析。

创建:

app/routes.php

<?php

use WangStruct\Routing\RouteCollection;

$routes = new RouteCollection();

$routes->add(
    'GET',
    '/',
    'IndexController',
    'index'
);

$routes->add(
    'GET',
    '/about',
    'IndexController',
    'about'
);

return $routes;

路由定义与路由执行分离:

  • routes.php 负责定义应用路由。

  • RouteCollection 负责保存路由。

  • Router 负责匹配当前请求。

  • Dispatcher 负责执行路由指定的控制器操作。

应用开发者可以增加路由定义,而不需要修改框架核心路由程序。

64.12 应用控制器实现

创建:

app/Controller/IndexController.php

<?php

namespace App\Controller;

use WangStruct\Http\Request;
use WangStruct\Http\Response;

class IndexController
{
    public function index(Request $request)
    {
        return new Response(
            json_encode(
                array(
                    'code' => 200,
                    'message' => 'WangStruct Framework Started',
                    'path' => $request->getUri()
                ),
                JSON_UNESCAPED_UNICODE
            )
        )->setHeader(
            'Content-Type',
            'application/json; charset=utf-8'
        );
    }

    public function about(Request $request)
    {
        return array(
            'code' => 200,
            'message' => 'About WangStruct Framework'
        );
    }
}

控制器不需要知道自动加载器如何查找文件,也不需要直接管理路由集合。

控制器只负责处理对应应用操作并返回结果。

64.13 框架统一启动入口

完成核心程序后,需要将 Web 访问入口调整为统一启动方式。

文件:

public/index.php

<?php

define('ROOT_PATH', dirname(__DIR__));

require ROOT_PATH
    . '/framework/Loader/Autoloader.php';

$loader = new \WangStruct\Loader\Autoloader();

$loader->addNamespace(
    'WangStruct',
    ROOT_PATH . '/framework'
);

$loader->addNamespace(
    'App',
    ROOT_PATH . '/app'
);

$loader->register();

try {

    $application = new \WangStruct\Core\Application(
        ROOT_PATH
    );

    $application->initialize();

    $application->run();

} catch (\Throwable $e) {

    http_response_code(500);

    header('Content-Type: text/plain; charset=utf-8');

    echo 'Framework runtime error.';

    error_log(
        $e->getMessage()
    );
}

这里使用 PHP 7 的 Throwable 接口捕获运行时异常和错误。该写法适用于 PHP 7 及以上版本。

生产环境不应直接向访问者显示内部异常信息,详细错误可以写入日志。

64.14 核心程序实际调用过程

本章的核心程序已经形成实际调用链。

以浏览器访问:

http://127.0.0.1:8000/about

为例。

64.14.1 程序执行过程

第一步:Web服务器将请求交给:

public/index.php

第二步:入口加载:

WangStruct\Loader\Autoloader

第三步:创建应用:

$application = new Application(ROOT_PATH);

第四步:执行:

$application->initialize();

第五步:Application 创建 Kernel,由 Kernel 加载配置、创建请求对象、加载路由和建立调度程序。

第六步:Kernel 执行:

$this->dispatcher->dispatch($this->request);

第七步:Router 获取请求方法和路径:

GET /about

第八步:路由匹配得到:

array(
    'method' => 'GET',
    'path' => '/about',
    'controller' => 'IndexController',
    'action' => 'about'
);

第九步:ControllerResolver 创建:

new \App\Controller\IndexController();

第十步:Dispatcher 调用:

$controller->about($request);

第十一步:控制器返回数据。

第十二步:调度程序将数据转换为 Response 对象。

第十三步:Application 调用:

$response->send();

最终返回:

{
    "code": 200,
    "message": "About WangStruct Framework"
}

64.14.2 完整调用关系

HTTP请求注册自动加载创建Applicationinitialize()创建Kernelinitialize()加载配置建立路由建立调度程序run()handle()dispatch(Request)match(Request)返回路由结果resolve(Controller)返回控制器对象调用控制器操作返回执行结果创建响应对象返回Response输出HTTP响应

64.15 核心程序运行验证

完成代码后,需要进行语法检查、自动加载检查、配置读取检查、路由匹配检查和 HTTP 访问检查。

64.15.1 PHP语法检查

在项目根目录执行:

php -l framework/Loader/Autoloader.php
php -l framework/Config/Config.php
php -l framework/Config/ConfigLoader.php
php -l framework/Http/Request.php
php -l framework/Http/Response.php
php -l framework/Routing/RouteCollection.php
php -l framework/Routing/Router.php
php -l framework/Application/ControllerResolver.php
php -l framework/Application/Dispatcher.php
php -l framework/Core/Kernel.php
php -l framework/Core/Application.php
php -l app/routes.php
php -l app/Controller/IndexController.php
php -l public/index.php

64.15.2 启动项目

执行:

php -S 127.0.0.1:8000 -t public

访问:

http://127.0.0.1:8000/

预期返回:

{
    "code": 200,
    "message": "WangStruct Framework Started",
    "path": "/"
}

再访问:

http://127.0.0.1:8000/about

预期返回:

{
    "code": 200,
    "message": "About WangStruct Framework"
}

访问不存在的地址:

http://127.0.0.1:8000/not-found

预期返回:

404 Not Found

64.15.3 测试结果判定

测试项目 验证内容 预期结果
自动加载 类名与文件路径映射 正确加载
配置加载 PHP配置文件读取 返回配置数组
请求读取 HTTP方法和路径 正确获取
路由匹配 请求路径和方法 返回正确路由
控制器定位 控制器类创建 成功创建
应用调度 控制器操作调用 正常执行
响应输出 响应状态和内容 正确返回
路由异常 不存在的路径 返回404

以上是本章的测试设计和预期结果。实际工程必须执行语法检查和 HTTP 测试后,才能确认具体环境中的运行结果。

64.16 核心程序职责边界

核心程序是框架的运行组织基础,但不能将所有组件功能集中到核心管理类中。

需要明确以下职责:

程序 负责内容 不负责内容
Application 框架启动和运行入口 具体业务处理
Kernel 核心对象初始化和协调 实现所有组件功能
Autoloader 类文件自动加载 对象生命周期管理
Config 配置数据读取与保存 数据库业务操作
Router 请求路由匹配 控制器业务执行
Dispatcher 控制器调用和结果转换 决策和智能行为
ControllerResolver 控制器定位和创建 控制器内部业务逻辑
Request 请求数据组织 路由规则定义
Response HTTP响应组织 业务结果判断

核心程序与后续组件的关系是:

  • 数据库组件负责数据库连接和数据操作。

  • 动态结构组件负责结构定义和管理。

  • 对象组件负责对象实例化和生命周期。

  • 知识组件负责知识管理。

  • 能力组件负责能力定义和调用。

  • 智能运行组件负责需求驱动的统一运行协调。

  • 执行组件负责任务执行与反馈。

  • 应用调度程序负责将外部请求交给对应应用程序。

核心程序只提供统一的运行基础,不替代这些组件的专业管理功能。

64.17 本章小结

本章根据前述架构设计,实现了 WangStruct Framework 核心程序的基础组织方式。

主要建立了:

  1. 框架自动加载程序。

  2. 配置数据管理和配置文件加载程序。

  3. HTTP请求与响应程序。

  4. 路由集合和路由匹配程序。

  5. 控制器定位程序。

  6. 应用调度程序。

  7. 核心管理类 Kernel。

  8. 框架应用入口 Application。

  9. 统一 Web 启动入口。

通过这些程序,框架已经形成从 HTTP 请求进入、自动加载类、初始化核心对象、读取配置、解析路由、调用控制器到输出响应的基础运行链条。

本章代码是基础核心程序的工程实现示例,后续正式开发时还需要继续完善动态路由、请求参数处理、依赖管理、异常分类、日志记录、响应格式、配置覆盖以及安全控制等机制。

核心程序的设计原则是:统一组织、明确分工、接口调用、独立扩展。 框架核心负责建立运行秩序,各专业组件负责自己的数据、结构和功能,应用程序通过公开接口使用框架能力。

Leave a Reply

Your email address will not be published. Required fields are marked *

客服咨询
● 欢迎咨询与合作
您好!欢迎咨询。 我可以帮助您了解人工智能技术研发、智能软件系统开发、网站建设、搜索优化及项目定制等相关信息。 请问有什么可以帮您?
免费申请
请填写以下信息,方便我们进一步沟通。
欢迎咨询 AI 系统开发、网站建设、搜索优化、项目定制合作
电话:15089196448
邮箱:1602401899@qq.com
地址:陕西省渭南市
服务时间:周一至周五 09:00 - 18:00 | 7×24小时技术值守