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 CSS实现渐隐虚线边框
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题