phpcomposer-phppackagist

how to set up composer package with packagist


I am trying to set up a composer package but i cannot seem to get it to load when i try it from a new project

my package is here https://github.com/shorif2000/pagination and the packgist is here https://packagist.org/packages/shorif2000/pagination

in a new project i have

{
    "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>

it fails with error 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. I tried use shorif2000\Pagination\Paginator; which gave same error as well


Solution

  • There's more than one issue here.

    composer.json (package)

    In your composer file (for the Pagination library), change PSR-0 to PSR-4. PSR-0 is an old format that was deprecated around 5 years ago (2014).

    Read more about PSR-4 here

    You should also always end the namespace with \\. So the package should be:

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

    Read more about composer autoload here

    Namespaces

    Since you're namespace is Pagination\, that's the namespace you should use in the code that uses it.

    So if you have a class with:

    namespace Pagination;
    
    class Pagination {
        ...
    }
    

    then your use statement should simply be:

    use Pagination\Pagination;
    

    Read more about PHP namespaces here

    The shorif2000 is the vendor name (which is only for composer to be able to group packages on vendor name and to remove the risk of different packages overwriting each other.

    Read more about composer vendor name here