首页 > 解决方案 > 如何使用 packagist 设置 composer 包

问题描述

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

我的包在这里https://github.com/shorif2000/pagination和 packgist 在这里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;了同样的错误

标签: phpcomposer-phppackagist

解决方案


这里的问题不止一个。

作曲家.json(包)

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

在此处阅读有关 PSR-4 的更多信息

您还应该始终以\\. 所以包应该是:

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

在此处阅读有关作曲家自动加载的更多信息

命名空间

既然你是 namespace is Pagination\,那就是你应该在使用它的代码中使用的命名空间。

因此,如果您有以下课程:

namespace Pagination;

class Pagination {
    ...
}

那么你的use陈述应该只是:

use Pagination\Pagination;

在此处阅读有关 PHP 命名空间的更多信息

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

在此处阅读有关作曲家供应商名称的更多信息


推荐阅读