简体   繁体   English

使用Composer和PSR-0进行命名空间自动加载无法正常工作

[英]Namespace autoloading with composer and PSR-0 not working as expected

I have made a test project to understand how composer and packagist works. 我做了一个测试项目,以了解作曲家和包装专家的工作方式。 The project is also on packagist . 该项目也在包装上

A simple composer require rakibtg/gowin will install the package from packagist. 一个简单的composer require rakibtg/gowin将安装composer require rakibtg/gowin的软件包。

But for some reason the namespacing is not working as expected. 但是由于某种原因,命名空间无法正常工作。

Here is my directory structure and the composer file. 这是我的目录结构和作曲家文件。 在此处输入图片说明

Here is the GoWin.php file: 这是GoWin.php文件:

  <?php

  namespace GoWin;

  class GoWin {
    public function serve() {
      echo 'Lets Win Everybody!';
    }
  }

Here is the test.php file where i am trying to use the serve() method from the GoWin class. 这是test.php文件,我正在其中尝试使用GoWin类中的serve()方法。

  <?php

  require_once './vendor/autoload.php';

  // use GoWin;

  ( new GoWin\GoWin() )->serve();

But it fails to execute the serve method with this error: 但是由于以下错误,它无法执行serve方法:

Fatal error: Uncaught Error: Class 'GoWin\\GoWin' not found in 致命错误:未捕获的错误:在中找不到类'GoWin \\ GoWin'

/Users/usr/Desktop/t estGoWin/index.php:7 Stack trace: / Users / usr / Desktop / t estGoWin / index.php:7堆栈跟踪:

0 {main} thrown in /Users/usr/Desktop/testGoWin/index.php on line 7 在第7行的/Users/usr/Desktop/testGoWin/index.php中抛出0 {main}

At this moment i cant understand what i am missing! 此时此刻我无法理解我所缺少的! Also should i use psr-0 or psr-4? 我还应该使用psr-0或psr-4吗?

I solved it by switching to PSR-4, simply update the composer.json autolaod property as this: 我通过切换到PSR-4解决了这个问题,只需将composer.json autolaod属性更新为:

"autoload": {
    "psr-4": {
        "GoWin\\": "src/"
    }
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM