DEV Community

Edgaras
Edgaras

Posted on

5 1 2 1

Crafting and Sharing Your PHP Library with Composer

Composer has become the backbone for managing dependencies and sharing reusable code. Whether you want to contribute to the open-source community or simply optimize your development workflow, learning to create a Composer package is a practical option. This post will take you through the process of building and sharing your own PHP library using Composer.

Prerequisites

Before you dive in, ensure you have the following:

  • Basic knowledge of PHP and Composer.
  • Composer installed on your system.
  • A GitHub (or other Git hosting) account.
  • A Packagist account for publishing your package.

Step 1: Setting Up Your Project

Start by creating a directory for your package. Open your terminal and run the following commands:

mkdir my-first-library
cd my-first-library
composer init
Enter fullscreen mode Exit fullscreen mode

The composer init command prompts you to fill in essential details like:

  • Package name: Use the format vendor/package (e.g., vendor-name/my-first-library).
  • Description: A brief overview of your library.
  • License: Choose an appropriate license (e.g., MIT).
  • Autoloading: Select PSR-4 for modern namespace-based loading.

This generates a composer.json file to define your package.

Create basic library structure

Set up directory structure for your library. Here’s a typical structure you can use:

my-first-library/
├── src/
│   └── MyMainLibClass.php
├── tests/
│   └── MyMainLibClassTests.php
├── .gitignore
├── composer.json
└── README.md
Enter fullscreen mode Exit fullscreen mode

Explanation of Each Component

  • src/: This directory contains the main PHP code for your library. Each class or functionality you write should reside here. For example, MyMainLibClass.php might be the entry point or a core class of your library.

  • tests/: This directory houses all test files for your library. Keeping tests separate from your main code ensures clarity and maintainability. For instance, MyMainLibClassTests.php will include unit tests for the MyMainLibClass.

  • .gitignore: This file specifies files and directories that Git should ignore, such as vendor/ (dependencies installed by Composer) and IDE-specific files.

  • composer.json: This is the heart of your package. It defines the package name, description, version, autoloading configuration, dependencies, and more. Use the composer init command to generate it.

  • README.md: This file serves as the documentation for your library. Include an overview, installation instructions, usage examples, and any other helpful information to guide users.

Step 2: Writing Your PHP Library

Add functionality to your library. For example, create a class for string manipulation:

// src/MyMainLibClass.php
namespace VendorName\MyFirstLibrary;

class MyMainLibClass
{
    public static function toUpperCase(string $input): string
    {
        return strtoupper($input);
    }
}

Enter fullscreen mode Exit fullscreen mode

Ensure your project uses PSR-4 autoloading by adding this to composer.json:

"autoload": {
    "psr-4": {
        "VendorName\\MyFirstLibrary\\": "src/"
    }
}
Enter fullscreen mode Exit fullscreen mode

Run composer dump-autoload to generate the autoloader.

Step 3: Adding Dependencies

If your library requires other packages, you can add them using Composer. For instance:

composer require some/dependency
Enter fullscreen mode Exit fullscreen mode

This updates the composer.json and installs the dependency. Make sure to use version constraints to ensure compatibility.

Step 4: Testing Your Library

Testing is crucial for building reliable libraries. Add PHPUnit to your project:

composer require --dev phpunit/phpunit
Enter fullscreen mode Exit fullscreen mode

Write your first test in the tests directory:

// tests/MyMainLibClassTests.php
use PHPUnit\Framework\TestCase;
use VendorName\MyFirstLibrary\MyMainLibClass;

class MyMainLibClassTests extends TestCase
{
    public function testToUpperCase()
    {
        $this->assertEquals('HELLO', MyMainLibClass::toUpperCase('hello'));
    }
}
Enter fullscreen mode Exit fullscreen mode

Run the tests:

vendor/bin/phpunit
Enter fullscreen mode Exit fullscreen mode

Step 5: Version Control with Git

Version control is essential for managing your code. Initialize a Git repository:

git init
git add .
git commit -m "Initial commit"
Enter fullscreen mode Exit fullscreen mode

Push your code to GitHub:

git remote add origin https://github.com/yourusername/my-first-library.git
git push -u origin main
Enter fullscreen mode Exit fullscreen mode

Use Git tags to manage versions:

git tag 1.0.0  
git push origin 1.0.0 
Enter fullscreen mode Exit fullscreen mode

Step 6: Publishing Your Package

To make your library available to others, publish it on Packagist:

  1. Create an account at Packagist.org.
  2. Submit your GitHub repository URL.

Repository must be public.

Step 7: Using Your Package

Once published, others can install your library using Composer:

composer require vendor-name/my-first-library
Enter fullscreen mode Exit fullscreen mode

And use it in their projects:

require 'vendor/autoload.php';

use VendorName\MyFirstLibrary\MyMainLibClass;

echo MyMainLibClass::toUpperCase('hello world');
Enter fullscreen mode Exit fullscreen mode

Step 8: Maintaining and Updating

Maintaining your package is as important as creating it. Follow these best practices:

  • Use Semantic Versioning (e.g., 1.0.0 for major releases).
  • Update dependencies regularly.
  • Respond to issues and pull requests if your library is open-source.

To release a new version, commit your changes, update the version number, and push the new tag:

git tag -a 1.1.0 -m "Added new feature"
git push origin 1.1.0
Enter fullscreen mode Exit fullscreen mode

Additional Resources

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay