PHP MVC命名空间和别名

时间:2017-01-02 19:01:36

标签: php model-view-controller namespaces aliases

我试图更好地学习PHP我的自定义框架(学习目的),我想知道如何实现带别名的命名空间(他们对我来说是新手)。我的#34;框架"结构看起来像:

app/
    controllers/
    core/
    functions/
    languages/
    models/
    vendor/
    views/
    .htaccess
    composer.json
    composer.lock
    config.php
    database.php
    filters.php
    index.php
    init.php
    routes.php
style/
upload/
.htaccess
index.php
robots.txt

在app / core文件夹中我有文件:

App.php
Controller.php
Filter.php
Functions.php
Language.php
Route.php
index.php

我的init.php文件如下:

<?php
    require "vendor/autoload.php";
    require "database.php";
    require "core/App.php";
    require "core/Filter.php";
    require "core/Route.php";
    require "functions/Common.php";
    require "functions/Validator.php";
    require "functions/Custom.php";
    require "core/Language.php";
    require "core/Functions.php";
    require "core/Controller.php";

来自controllers /文件夹的文件扩展了Controller.php,core / Functions.php扩展了core / Custom.php,扩展了core / Common.php 我如何实现命名空间和alisaing,这样我可以使我的框架更容易维护,而不需要使用完整的命名空间加载每个类?提前致谢

修改: 好的我已经在app / controllers /中使用此代码

创建了一个文件controller.php
<?php
    use App\Core\Controller as BaseController;

    class Controller extends BaseController {

    }

在我的App.php中,我添加了以下功能:

    private function applyAliases() {
        foreach(self::$config['aliases'] as $file => $alias) {
            class_alias($file, $alias);
        }
    }

所以在我的config.php文件中我添加了:

/* Aliases */
"aliases" => [
    "App\Core\Language" => "Language",
    "App\Core\Filter" => "Filter",
    "App\Core\Route" => "Route"
]

另外,在Functions.php中加载函数时我添加了另一个class_alias:

public function loadFunction(string $file) {
    if(!file_exists(App::$config['paths']['functions'].$file.".php")) {
        throw new Exception("File ".App::$config['paths']['functions'].$file.".php doesn't exists");
    }

    require App::$config['paths']['functions'].$file.".php";

    class_alias("App\Functions\\".$file, $file);

    return new $file();
}

这会是正确的方法吗?

0 个答案:

没有答案