doumo3903 2015-09-26 21:23
浏览 263
已采纳

Composer自动加载文件无法正常工作

My Autoload specification are as follows

  "autoload" : {
        "psr-4" : {
            "MyMVC\\" : "app/"
        },
        "classmap": [
            "app/Controllers",
            "app/Helpers"
        ],
        "files": ["app/routes.php"]
    },

The contents of routes.php file are:

<?php
use MyMVC\Core\Route;

$route = new Route;
$route->add('/', 'HomeController@index');
$route->add('about', 'AboutController@index');
$route->add('contact', 'ContactController@index');

now in my app/init.php i am trying to use the $route object but its giving me error

Notice: Undefined variable: route in /var/www/html/mymvc/app/init.php on line 29

Here is how i am trying to use the $route object.

/**
 * Constructor
 * Bootstrap our application based on the configurations provided
 */
public function __construct()
{
    // require 'app/routes.php` This will work fine but it should be autoloaded
    var_dump($route);
    exit;
}

I have also ran command composer dump-autoload

  • 写回答

1条回答 默认 最新

  • duanjiashai9140 2015-09-27 23:46
    关注

    Autoloading won't work here. PHP can only autoload classes. Your expectation that app/routes.php will be autoloaded is not possible, because that file does not contain a class declaration, and you are not able to trigger it's execution by using a previously unknown class.

    It is true that Composer will execute that file once when you include vendor/autoload.php - however, this is really bad behavior of your software. Don't use the "files" autoloading to include configuration files. Mind the performance impact this may have when being used in libraries. You should avoid using it altogether, it is meant to be used for legacy code that cannot otherwise be made working.

    On the other hand, your architecture is broken. You shouldn't write a class that "magically" knows about the configuration just by accessing a variable that is supposed to be initialized somewhere else. A good pattern would be to pass the configuration as a parameter to the constructor:

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

    The part of the code that creates this class is supposed to grab the configuration from somewhere and pass it as a parameter. This concept is called inversion of control or dependency injection: Classes do not invoke the other classes they need to work with, they ask for them and get them as a parameter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c