Creating your first Composer/Packagist package

Hi everybody! Today I’ll write about how you can contribute with PHP community creating packages (or updating your’s) using Composer and Packagist. First, if you’re a PHP developer and don’t know yet what is Composer, take a look on the post Why you should use Composer and how to start using it to get more information about.

Using Composer

Composer is a package manager for PHP. You can use packages the community developed and you can contribute with your packages too. Here I’ll show how to create a project/package, install Composer inside it and send to Packagist, where others developers can use it inside their projects.

Creating the Package

You can create a new project or update one to use Composer. I’ll create a hello world class. It’s a simple class but you can create complex projects and share them with the others developers. I’ll use “hello-world” as project’s name. Composer work in “vendor/package” name format. Here we can set as “vendor” name my name: “juniorgrossi” and as package name “hello-world”, the name of the project.

Files Structure

You can put all files inside the main dir, but I strongly recommend to create another dir, as “src” to be easier to understand and maintain your code organized. The project structure will start with the follow: hello-world/src/HelloWorld/SayHello.php. Our SayHello.php file will have:

<?php 

namespace HelloWorld;

class SayHello
{
    public static function world()
    {
        return 'Hello World, Composer!';
    }
}

Starting Composer

As our project is ready we can “install” Composer inside it. This is only create a “composer.json” file inside root dir, but Composer can do that for you. Inside your project root: composer init You’ll have the follow Composer response:

macbook:hello-world grossi$ composer init


  Welcome to the Composer config generator  



This command will guide you through creating your composer.json config.

Package name (/) [juniorgrossi/hello-world]:
 You can accept the default or customize it like "yourname/hello" or what you want. Complete all Composer questions like: 

Package name (/) [juniorgrossi/hello-world]: juniorgrossi/hello-world
Description []: My first Composer project
Author [Junior Grossi <me@juniorgrossi.com>]: Your Name <your@name.com>
Minimum Stability []: dev

Define your dependencies.

Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no

{
    "name": "juniorgrossi/hello-world",
    "description": "My first Composer project",
    "authors": [
        {
            "name": "Your Name",
            "email": "your@name.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {

    }
}

Do you confirm generation [yes]? yes

Now you have “composer.json” file saved in your root dir. It’s almost ready but we must do some changes:

{
    "name": "juniorgrossi/hello-world",
    "description": "My first Composer project",
    "authors": [
        {
            "name": "Your Name",
            "email": "your@name.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {
        "php": ">=5.3.0"
    },
    "autoload": {
        "psr-0": {
            "HelloWorld": "src/"
        }
    }
}

What we did here is add information about PHP 5.3 as minimum requirements (require section) and tell Composer to “autoload” (using PSR-0) all files with “HelloWorld” namespace that are inside “src” dir.

Testing Package

Shure we want to do a simple test to verify if our class is working well. You can create a new project and “paste” your classes inside it or test inside your own project, wich is better and easier. We’re creating a Composer project so we must have Composer files installed inside our projects. So, install it running “composer install” inside your root dir:

composer install

As you have only “php >=5.3.0” inside “composer.json”, Composer will install only it’s own files. With Composer installed create a directory “tests” inside your root dir. Create the “test.php” file inside it with the follow content:

<?php 

require_once __DIR__ . '/../vendor/autoload.php'; // Autoload files using Composer autoload

use HelloWorld\SayHello;

echo SayHello::world();

Go to the terminal (or create a PHP web server inside “tests” dir) and type:

php tests/test.php

You’ll get “Hello World, Composer!”. It’s working now.

Sending to Packagist.org

Now your project is working and you want to send it to Packagist. The easy way is push your project to Github using Git. Go to Github and create a new public repo called “helloworld”, start the Git project inside your root dir and push it:

git init 
git add . 
git commit -m "First commit" 
git remote add origin git@github.com:username/helloworld.git 
git push origin master

Now you have your project inside a Github repo and you’re ready to send it to Packagist. Go to Packagist web site, create your account, login and Submit a Package. Packagist’ll ask you for Repository URL (Git/Svn/Hg). Paste there git@github.com:username/helloworld.git and click “Check!”. Packagist will check your project and return the project name. If it’s correct accept it.

Packagist Details

Every time you do a new commit to Github you must update the Packagist. Go to your account, your package and click “Force Update!”. Packagist will go to Github and update the sources. You can turn on “auto update” going to your Github repo, clicking “Settings”, after “Service Hooks” and click the “Packagist” service. There update with your information, like:

  • User: your Packagist username, like juniorgrossi
  • Token: your API token, that you can find inside your Packagist settings link
  • Domain: packagist.org Ok! Auto update finished and your package is available to other developers.

Our first Composer package is finished, but you can do much more using it. Thanks!

Published by

Junior Grossi

senior software engineer & stutterer conference speaker. happy husband & dad. maintains Corcel PHP, elePHPant.me and PHPMG. Engineering Manager @ Paddle

91 thoughts on “Creating your first Composer/Packagist package”

  1. Olá buenas amigo eu segui os passos e consegui criar o arquivo composer.json só que tive uma msg de erro no terminal ao instalar o comando “composer install” alerta: Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.

    1. if your package is public, just send it to packagist and you’re good to go. otherwise you can have it on a git repo and point your composer.json file to it. even if it’s private, just setup the correct ssh keys and permissions on github or any other git service and you’re also fine.

  2. Hi Grossi,
    I follow step by step as you given above in doc but i am getting this error when i installed my package

    Your requirements could not be resolved to an installable set of packages.

    Problem 1
    – The requested package cvam/hello-composer * is satisfiable by cvam/hello-composer[dev-master] but these conflict with your requirements or minimum-stability.

    Installation failed, reverting ./composer.json to its original content.

    Please help me

    1. hey! thanks for commenting! you should create a new release in GitHub. release in GH is just a tag they create (think in it like a snapshot), then you start versioning your package. let me know if you have any more questions! cheers!

  3. Hi thanks for this good article. Yousaid ” The easy way is push your project to Github using Git” Is there another way to publish package without Github?

  4. Nice Tutorial

    But i have one problem, I follow all steps including submitting package Packagist website and
    all goes well. When I try to install the package using “composer require ” I receive following:

    [InvalidArgumentException]

    Could not find package nilay/vk-php-sdk at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

    I also create package and put it on github & packagist

    https://packagist.org/packa

    1. The ‘InvalidArgumentException’ error occurs because you have ‘minimum-stability’ in composer.json file, because of that you would need to require the package by using:

      composer require mypackage/package-name:dev-master

      Alternatively you can remove ‘minimum-stability’ from composer.json, push changes to github, update package in Packagist and then you can use:

      composer require mypackage/package-name

  5. I follow all steps including submitting package Packagist website and

    all goes well. When I try to install the package using “composer
    require ” I receive following:

    [InvalidArgumentException]

    Could not find package nilay/vk-php-sdk at any version for your
    minimum-stability (stable). Check the package spelling or your
    minimum-stability

    I also create a package and put it on github & packagist

    Link : https://packagist.org/packa

      1. As per your suggesstion i set in composer.json file.

        But then also When I try to install the package using “composer
        require ” I receive same error.

        Please suggest me….

        1. Hi Kel! What issue are you getting? Your composer.json file seems to be fine. What’s the problem?

          1. Hey, it seems the package is not registered in packagist.org. You have to create an account in there and submit your package, linking it to your git repo.

  6. Thank you, thank you, thank you. I spent days trying to find out why my package wouldn’t load, and this article finally helped me get the correct set of package name, namespace in the class and composer.json pointing to the correct class name with matching filename.

  7. I am creating a stand-alone package, seen this article and it helped me a lot. Can you please help me out how can I generate views/config like I want to extract some files outside the vendor directory when someone install my package from packagist by composer command?

      1. Thanks for your quick response, but I am not creating a package for specific framework. It will be stand-alone php(utility) I want to extract some files outside the vendor directory as I mentioned. I have posted my question at stackoverflow http://stackoverflow.com/qu… please help me out. Thanks.

  8. I falowed the steps here and i get the error :

    PHP Fatal error: Uncaught Error: Class ‘HelloWorldSayHello’ not found

    so the issue in my case was that the composer.json file didn’t had the autoload psr-0 mapper

    ….
    “autoload”: {
    “psr-0”: {
    “HelloWorld”: “src/”
    }
    }

    I add that and run composer install again and fix it

      1. Cool Thanks I’m bit new in composer , so in your case using psr-4 should be something like this :

        “autoload”: {
        “psr-4”: {
        “HelloWorld\”: “src\HelloWorld\”
        }
        }

        1. Yes! Or you can omit the `HelloWorld` folder. So you can have your classes in `src/MyClass.php` and `src/AnotherClass.php`. Inside each one you should say `namespace MyPackageName`, just that.

  9. Thank you for the post.Following message came when I try to submit in packagist
    “The package name was not found in the composer.json, make sure there is a name present.”
    {
    “name”: “karter/test”,
    “description”: “test package for packagist”,
    “type”: “library”,
    “require”: {
    “php”: “>=5.3”
    },
    “license”: “MIT”,
    “authors”: [
    {
    “name”: “karterpaul”,
    “email”: “karterpauls@gmail.com”
    }
    ],
    “minimum-stability”: “dev”,
    “autoload”: {
    “psr-4”: {
    “Karter\Test\”: “src/”
    }
    }
    }

    1. Hi Karter. I cannot help you without more information about your project. The composer.json file seems to be ok, but maybe you’re doing something wrong during the process. Another topic is to not upload a package as ‘test’. If the package is not ready yet it’s not time to publish on packagist.org. You don’t have to publish your package to use it, just set the Github URL and you still can install it using composer. Take a look https://getcomposer.org/doc…. Again, only send your package to packagist if it’s ready and if it does not exist yet. Best regards.

  10. Thanks a lot for you post, i just need to know more about composer, eg. how to make a version to stable and how to handle dev version?

    i’m trying to convert my own framework from old-php mode to build to more smarter version to composer look here https://packagist.org/packa… its say master-dev version, i think its will be nice to have more version but i don’t know how 🙂

    Thanks agin for your posting.

    1. Hi @Paris. Thanks for the message.

      Project’s versions are based on the last release/tag in the Git repo. Let’s suppose you have your project in Github, so if you have only the master branch and no release you have only the master-dev version.

      Then you should go to “releases” inside your repo page and create a new one, something like v1.0.0 or v0.3.0. When you create this release it will be automatically sent to packagist and the user can set the version he wants.

      Best regards.

  11. Hello,
    i want to add this project created to an application php/laravel how can i do ??
    Regard

    1. Hi @Mohamed! You must send it to Packagist.org first and after include it inside your composer.json file and run “composer install”. Any question just ask. Best!

  12. Ty for the tutorial, it was very cool, but there are a problem using this package with my project , after calling composer require package name the error come up

    [InvalidArgumentException]
    Could not find package mkdesignn/hello-world at any version for your minimu
    m-stability (stable). Check the package spelling or your minimum-stability

    but i dont know where is the problem may you help me to figure it out , coz its really make me crazy .
    ty for any help .

    1. Hi @mohammad! Did you send the package to packagist.org? You have to set a minimum-stability value inside composer.json to let packagist to know what branch (for example) it has to download. Thanks for the comment 🙂

  13. Hello Again,

    I did the same procedure you did, when I run the php test/php in my root directory it’s giving an error:

    Fatal error: Class ‘HelloWorldSayHello’ not found in /data/home/username/hello-world/tests/test.php on line 8

    Call Stack:

    0.0003 219896 1. {main}() /data/home/username/hello-world/tests/test.php:0

    Thanks for your time and help.
    -PM

    1. Hi @PM! Your error is “Fatal error: Class ‘HelloWorldSayHello’ not found “. The class SayHello inside HelloWord namespace does not exists. So, you are on the main namespace so you have to call the class as “HelloWordSayHello”, with backslash first. Regards.

  14. Hello Junior Grossi!

    Tank you for sharing! I am working in a symfony project which has web services. And now I am working on the Client Library for this web services which is in a different repository. Eventually this client library should live in Client Application (we have several internal applications with in the organization). This Client Library I put in a GitLab, is that enough or I SHOULD put it in a Packagist.org? Please guide me. I tried installing this Client Library (before putting into packagist) with in the Client Application, it didn’t work. It is giving a below message:
    ————————————————————————–
    Your requirements could not be resolved to an
    installable set of packages.

    Problem 1

    – The requested package
    username/wsclient could not be found in any version, there may
    be a typo in the package name.

    Potential causes:

    – A typo in the package name

    – The package is not available in a stable-enough version according to your
    minimum-stability setting

    see groups.google.com=”” d=”” topic=”” composer-dev=”” _g3aseiflrc=”” discussion=””>
    for more details.

    Read getcomposer.org=”” doc=”” articles=”” troubleshooting.md=””>
    for further common problems.

    ————————————————————————

    Because this code is proprietary this should not live in a public accessible website. Please guide me to solve this problem.

  15. I follow all steps including submitting package Packagist website and all goes well. When I try to install the package using “composer require ” I receive following:

    [InvalidArgumentException]
    Could not find package nilay/vk-php-sdk at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

    1. Hi @Nilay! Did you send your package to http://packagist.org? For example, you have to send your repo to Github or Bitbucket and create the package inside Packagist, syncing with your repo. Only after you’ve created the package inside Packagist you can install it using composer. If you have any questions just ask. Thanks for the comment. 😉

  16. Am I missing something here? The “Creating the Package” section doesn’t actually show how to create the package. Is the package created using a command on the CL? Is there a default framework used? If no command, is there a structure to the files? The link to “Why Composer…” is dead.

    1. Hi @Richard! All links were fixed. Please, try again 😉
      The package is created using “composer init”. Cheers!

  17. First time I did these steps – everything worked. Now in another fresh directory I cannot make it work. After I run composer isntall, I get:

    Loading composer repositories with package information

    Installing dependencies (including require-dev)

    Nothing to install or update

    Generating autoload files

    I see vendor folder is generated with files in it.

    I run:

    php tests/test.php

    PHP Fatal error: Class ‘HelloWorldSayHello’ not found in /home/vagrant/package_dev/workbench/oitlabs/HelloWorld/tests/test.php on line 7

    Can you explain why it does not find? How to check?

    Also its interesting that it says – nothing to install or update. I don’t remeber if I got same output when I first time succesfully did this

    1. Hi @Speed_FANat1c!

      You can type composer init first and it will create the composer.json for you with the packages you want.

      Any questions just ask.

      Cheers!

      1. Found the problem. In src directory I had to create HelloWorld directory. Somehow harder to see structure from this:
        “The project structure will start with the follow: * hello-world (root dir) * src * HelloWorld * SayHello.php Our SayHello.php”

        I would suggest update and make a screen shot of file structure or something which could be more clear to see 🙂

        1. Hi!

          Thanks for the comment. The directory is right, because it can change according your autoload configuration in the composer.json file.

          In my case I have the HelloWorld directory too and inside it the PHP files. This is describe in the composer.json file.

          Thanks for the comment and any question just ask.

          Cheers!

          1. the src folder is not clear.. but i manage to do it.
            so the folder should be like this,

            C:….hello-worldsrcHelloWorldSayHello.php

            Thanks for the info 😀

  18. Thanks for the tutorial. I think this is most straight forward one that I have come across.

    I have followed every step of the way and have saved my zf2 package under vendor. inside vendor, I have juworld/jumodule/ and that is where I created my composer.json. I also modified it as suggested:

    ...
    "require": {
    "php": ">=5.3.0"
    },
    "autoload": {
    "psr-0": {
    "JuModule": "src/"
    },
    "classmap": [
    "./Module.php"
    ]
    }

    Now, I ran composer install (or composer update) in the vendor’s directory (../vendor). I noticed my module is not loaded to my zf2.

    I looked up vendor/composer/autoload_classmap.php and autoload_namespaces.php, and I noticed my module is not added.

    What am I missing here?

    Thanks in advance!

    Justin

  19. Sometimes I see that in the /src folder another foldername with the authors name is created.
    What is the best practice?
    /src/Geolocation/Geolocation.php or /src/JeroenDesloovere/Geolocation/Geolocation.php

    1. Hi Jeroen! You do not have a rule to that. Even you can have /src/Geolocation.php. The Composer will map the author/package path.

  20. Finally figured out what I was doing wrong so really appreciate it. Thank you for writing this up.

Leave a Reply

Your email address will not be published. Required fields are marked *