我正在为我的投资组合编写一个轻量级的 php mvc 框架,并作为我未来发展的准系统设置。我现在被卡住了,因为我试图通过作曲家使用 PSR-4 自动加载器。我了解 PSR-4 等的概念,但我想知道我应该如何处理路由。
我的文件夹结构是:
--|-Root---
index.php
composer.json
-----|-application------
--------|-controller----
--------|-model---------
--------|-core----------
-----------|-baseController.php
-----------|-Application.php
-----------|-baseView.php
-----------|-baseModel.php
--------|-view----------
--------|-config
-----------|-config.php
-----|-vendor------
--------|-autoload.php
-----|-assets------
我对 php 相当熟悉,但编写自己的 mvc 框架是一项艰巨的挑战,甚至更大,因为我以前从未使用过 PSR 标准。
现在我的问题是:
- 我应该使用路由器吗?
- 如果是,那么我应该使用什么模式来完成它。
因此,在我的 index.php 中,我定义了所有常量来存储 ROOT、APP、VENDOR 等目录。然后我加载从我的 composer.json 生成的 vendor/autoload.php。在 autoload.php 之后,我通过调用以下代码加载并启动我的配置:
if(is_readable(APP . 'config/config.php'))
{
require APP . 'config/config.php';
//Initiate config
new AppWorld\Confyy\config();
}
else
{
throw new Exception('config.php file was not found in' . APP . 'config');
}
配置后我设置应用程序环境,然后我通过调用启动我的应用程序:
// Start the application
new AppWorld\FrostHeart\Application();
然后我的 baseController 非常非常薄:
<?php
namespace AppWorld\FrostHeart;
use AppWorld\FrostHeart\baseView as View;
abstract class baseController {
public $currentView;
public function __construct() {
//Initiate new View object and set currentView to this object.
$this->currentView = new View();
}
}
这是我的 baseView.php:
<?php
namespace AppWorld\FrostHeart;
class baseView {
public function show($file, $data = null, $showTemplate = 1) {
if($data != null) {
foreach($data as $key => $value) {
$this->{$key} = $value;
}
}
if($showTemplate === 1) {
require VIEW_DIR . header . ".php";
require VIEW_DIR . $file . ".php";
require VIEW_DIR . footer . ".php";
}
elseif($showTemplate === 0)
{
require VIEW_DIR . $file . ".php";
}
}
}
我的 config.php:
<?php
namespace AppWorld\Confyy;
class config {
public function __construct() {
$this->application();
$this->database();
}
public function application() {
/**
* Define application environment, defaults are:
*
* development
* live
*
*/
define("ENVIRONMENT", "development");
//Define base url
define("BASE_URL", "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
//Define default controller
define("DEFAULT_CONTROLLER", "landing");
//Define default method
define("DEFAULT_METHOD", "index");
//Define controllers directory
define("CONTROLLER_DIR", APP . "controller/");
//Define views directory
define("VIEW_DIR", APP . "view/");
}
public function database() {
//Define DB Server
define("DB_SERVER", "localhost");
//Define DB User
define("DB_USER", "root");
//Define DB Password
define("DB_PASSWORD", "");
//Define DB Name
define("DB_NAME", "test");
}
}
最后是我的 composer.json 自动加载部分:
"autoload": {
"psr-4":{
"AppWorld\\": "application",
"AppWorld\\Conffy\\": "application/config",
"AppWorld\\FrostHeart\\": "application/core",
"AppWorld\\Controls\\": "application/controller"
}
}
那么我应该如何实现路由 URL 请求并加载正确文件的路由器呢?
谢谢!