Composer 自动加载完整示例? [英] Composer autoload full example?

查看:43
本文介绍了Composer 自动加载完整示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 all 和平 一起我发现了关于自动加载作曲家的课程,但我无法让它发挥作用.我看到的每个例子都缺少某些部分.基本上它归结为两个 4 行的文件:

I am trying to put all the peaces together I found about autoloading a class in composer but I can't make it work. Every example I see is missing some part. Basically it comes down to two files with 4 lines:

index.php

$loader = require 'vendor/autoload.php';
$loader->add('Vendor\', __DIR__.'/../app/');
new Vendor_Package_Obj();

app/Vendor/Package/Obj.php

app/Vendor/Package/Obj.php

class Obj {}

我还尝试了 psr-4 和所有可能的文件夹和名称的组合,用于供应商包对象?但没有找到可行的解决方案.

I also tried psr-4 and all thinkable combinations of folders and names for `Vendor Package Obj? but no luck finding a working solution.

如何使用 Composer 使用任何这些标准自动加载文件?

How can I autoload a file with composer using any of those standards?

推荐答案

根据 PSR-4,全限定类名必须有一个顶级命名空间,也称为供应商命名空间",下划线在全限定类名的任何部分都没有特殊含义.

According to PSR-4, The fully qualified class name MUST have a top-level namespace name, also known as a "vendor namespace" and underscores have no special meaning in any portion of the fully qualified class name.

试试这个:

cd ~
mkdir -p testproj/src/MyApp/Package
cd testproj
composer init && composer update

使用以下内容创建您的 index.php:

Create your index.php with this content:

<?php
$loader = require 'vendor/autoload.php';
$loader->add('MyApp\', __DIR__.'/src/');
$a = new MyAppPackageObj();
var_dump($a);

并放入 Obj 类 (src/MyApp/Package/Obj.php) :

And put the Obj class (src/MyApp/Package/Obj.php) :

<?php
namespace MyAppPackage;

class Obj
{}

现在当你运行代码时:

php index.php

你应该得到这个作为输出:

You should get this as output:

class MyAppPackageObj#2 (0) {
}

此外,目录脚手架应如下所示:

Also directory scaffolding should look like this:

testproj
├── composer.json
├── index.php
├── src
│   └── MyApp
│       └── Package
│           └── Obj.php
└── vendor
    ├── autoload.php
    └── composer
        ├── ClassLoader.php
        ├── autoload_classmap.php
        ├── autoload_namespaces.php
        ├── autoload_psr4.php
        └── autoload_real.php

这篇关于Composer 自动加载完整示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆