【发布时间】:2019-06-23 06:11:58
【问题描述】:
我使用 MVC 结构 处理自己的项目,并使用 composer 使用 PSR-4 自动加载类。我为我的路由器引擎选择 Php Fastroute 库。
我的结构是:
index.php
define('DS', DIRECTORY_SEPARATOR, true);
define('BASE_PATH', dirname(__DIR__) . DS, TRUE);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require '../vendor/autoload.php';
require '../application/core/Core.php';
// Our framework is now handling itself the request
$app = new Framework\Core();
$response = $app->handle();
控制器:
namespace App\Core;
class Controller
{
public $templates;
public function __construct()
{
// My Question
$this->config = new \App\Core\Setting();
$this->Language = new Language('en');
$this->Url = new \App\Core\Url(Config::get('URL'),Config::get('URL'));
$this->templates = new \League\PlatesEngine(Config::get('PATH_VIEW'));
$this->Document = new \App\Core\Document();
}
public function loadModel($name, $path = null) {
$path = ($path === null) ? 'Catalog' : $path;
$path = '\App\\'.$path.'\Model\\'.$name;
$this->model = new $path;
return $this->model;
}
public function loadController($name) {
$path = '\App\Catalog\Controller\\'.$name;
$this->controller = new $path;
return $this->controller;
}
}
索引控制器:
namespace App\Catalog\Controller\Home;
class IndexController extends \App\Core\Controller
{
public function index()
{
$add['power'] = $this->config->get('on');
$data['title'] = $this->Language->get('text_title');
$this->templates->addData($data, 'common/header');
//.... More Code
}
}
在行动中,我将类新实例(库和核心类,即:Config 或 Ducoment 或 Templates 或更多,如果需要...)放在 Bridge Controller 的 __construct() 中并扩展 IndexController。这个模型对我有用但我不知道这个方法是真是假?!实际上,我需要将对象(新实例)从核心类加载到我的IndexController 但我不知道它会放在哪里(更好和真实)?! (在Base Controller - 在IndexController - 在Core.php and require - 在Index.php)??
【问题讨论】:
-
至少可以在 index.php 中新建配置、url 和语言,然后传递给 $app = new Framework\Core($config,$url,$language);
-
这个问题没有正确或错误的答案。最好的方法是什么,这是一个见仁见智的问题。没有“PHP MVC 结构”之类的东西。
-
@jrswgtr:你的意思是什么:
There is no such thing as "The PHP MVC structure" -
MVC 结构是 PHP 本身不存在的东西。人们在构建框架或应用程序时自己实现它。这意味着没有完全错误或正确的方法来做到这一点。有更好和更坏的方法,但这是见仁见智的问题。
-
@jrswgtr:当然,我添加这个问题是为了分享更好的想法(更好和更坏的方式)。