如何使用 packagist 设置 composer 包

how to set up composer package with packagist

我正在尝试设置一个 composer 包,但是当我从一个新项目尝试它时我似乎无法加载它

我的包裹在这里https://github.com/shorif2000/pagination and the packgist is here https://packagist.org/packages/shorif2000/pagination

我有一个新项目

{
    "name": "ec2-user/pagination",
    "authors": [
        {
            "name": "shorif2000",
            "email": "shorif2000@gmail.com"
        }
    ],
    "require": {
        "shorif2000/pagination": "dev-master"
    },
    "minimum-stability" : "dev"
}

$ cat index.php
<?php

require './vendor/autoload.php';

use Pagination\Paginator;

$totalItems = 1000;
$itemsPerPage = 50;
$currentPage = 8;
$urlPattern = '/foo/page/(:num)';

$paginator = new Paginator($totalItems, $itemsPerPage, $currentPage, $urlPattern);

?>
<html>
  <head>
    <!-- The default, built-in template supports the Twitter Bootstrap pagination styles. -->
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  </head>
  <body>

    <?php
      // Example of rendering the pagination control with the built-in template.
      // See below for information about using other templates or custom rendering.

      echo $paginator;
    ?>

  </body>
</html>

失败并出现错误 Fatal error: Uncaught Error: Class 'Pagination\Paginator' not found in /opt/pagination/index.php:12 Stack trace: #0 {main} thrown in /opt/pagination/index.php on line 12。我试过 use shorif2000\Pagination\Paginator; 也给出了同样的错误

这里的问题不止一个。

composer.json(包)

在您的作曲家文件中(对于分页库),将 PSR-0 更改为 PSR-4PSR-0 是大约 5 年前(2014 年)已弃用的旧格式。

Read more about PSR-4 here

您还应该始终以 \ 结束命名空间。所以包裹应该是:

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

Read more about composer autoload here

命名空间

由于您的命名空间是 Pagination\,这就是您应该在使用它的代码中使用的命名空间。

因此,如果您有 class 并且:

namespace Pagination;

class Pagination {
    ...
}

那么您的 use 语句应该只是:

use Pagination\Pagination;

Read more about PHP namespaces here

shorif2000 是供应商名称(仅供作曲家根据供应商名称对包进行分组并消除不同包相互覆盖的风险。

Read more about composer vendor name here