PHP: How to create a composer package

If you are reading this I guess you know what Composer and Packagist are and probably you need to know how to build your own package or you just simply don’t remember all the steps to do it.

Otherwise, you can get some very basic info of Composer here: Wikipedia Composer and if you want to dive into the documentation then you can visit Composer Documentation page. Packagist is the main repository for Composer packages.


We will create a package and before writing a line of code, we will compile some basic information. I’m using mine as an example.

  • Developer name / Organization: pangodream
  • Package name: str-util
  • Description: A very simple package

Setting up the project for the package

Create the project folder

In our case, the project folder will be str-util

Create two more folders inside the project one; one for the package code and the other one for testing. The folder structure should be:

Create composer.json file

Access the project folder and create composer.json by typing 

> composer init

Composer will try to guess some of the configuration values

Once we confirm the file generation, a composer.json file will be in our project folder and it will contain some very similar to this:

    "name": "pangodream/str-util",
    "description": "A very simple package",
    "type": "library",
    "license": "MIT",
    "authors": [
            "name": "pangodream",
            "email": ""
    "minimum-stability": "dev",
    "require": {}

So, this is now the content of our project folder:

Edit to complete composer.json

We will add some information about autoloading (“autoload”) and also tell composer our dependencies (“require”). For instance, which is the minimum version of PHP that our library needs to work.

    "name": "pangodream/str-util",
    "description": "A very simple package",
    "type": "library",
    "license": "MIT",
    "authors": [
            "name": "pangodream",
            "email": ""
    "minimum-stability": "dev",
    "autoload": {
        "psr-0": {
             "StrUtil": "src/"
    "require": {
        "php": ">=7.0.0"
Install composer autoloader

Now we will tell Composer to install autoloader and its code. Like any other vendor, Composer will deploy its own files inside the vendor folder.

> composer install
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Writing lock file
Generating autoload files

Now, the content of the folder is

Write down our package code

Inside the composer.json file, we told composer the path were StrUtil package classes are. So, each time we reference in our code a class qualified with its package name Composer will look into the composer.json file to know where that class file is.

In our case, the package name is StrUtil and the class is Counter (because our class will contain some methods to count words, paragraphs, letters, …).

Inside src folder, let’s create a new folder for our package with the name we gave it inside composer.json: StrUtil, and inside that folder, we will place one of our package classes file. Now, we have this folder hierarchy 


So, when PHP finds a reference to a class with the ‘use’, it will look into composer.json. For instance, let’s say we have a line of code like this

use StrUtil\Counter;

What composer.json file indicates is that StrUtil package is under src folder

"autoload": {
        "psr-0": {
            "StrUtil": "src/"

So, the Counter.php file containing the Counter class code should be located in


Now we know how the class file is located and loaded, let’s write down the code:

 * Created by Pangodream.
 * Date: 14/04/2019
 * Time: 18:50

namespace StrUtil;

class Counter
     * @param string $text The text we want to count the number of words it consist of
     * @return int The number of words in text
    public static function countWords(string $text){
        /** @var int $count To store the result of counting words in text */
        $count = 0;
        //Clean up the string
        $text = trim($text);
        /** @var array $words Array containing the words */
        $words = explode(" ", $text);
        //Array size is the number of words in text
        $count = sizeof($words);
        return $count;

And now we know how to reference that class, let’s create a test file to verify that our class works. We will name this file testStrUtil.php and save it inside the test folder we created before:

 * Created by Pangodream.
 * Date: 14/04/2019
 * Time: 19:03

//Use composer autoload to load class files
require_once __DIR__ . "/../vendor/autoload.php";

//Required package/libraries
use StrUtil\Counter;

$text = "Aequam memento rebus in arduis servare mentem";
$wordCount = Counter::countWords($text);
echo "The txt contains ".$wordCount." word(s)\r\n";
Testing our package

From the str-util folder, we are going to invoke the test PHP file and see what happens:

str-util> php test/testStrUtil.php
The text contains 7 word(s)

Our package containing only a class is working and now we are ready to publish it.

Repository part:

The next thing we’ll do is creating a new repository with our GitHub account.

Create the repository at

Go to and create a new repository called str-util. It is a good practice to give a repository description and also initialize with a README file. Because you are going to share the package in you need to Add a license file, in our case an MIT License.

Add package files to the repository

Now we will make an initial commit to our repository with the files we already have created inside the src folder.

From the str-util folder, execute the following commands:

---->str-util> git init
Initialized empty Git repository in C:/cli/str-util/.git/

---->str-util> git add src
---->str-util> git add composer.json ---->str-util> git commit -m "Initial commit" [master (root-commit) af7bbac] Initial commit 2 file changed, 28 insertions(+) create mode 100644 src/StrUtil/Counter.php
create mode 100644 composer.json ---->str-util> git remote add origin ---->str-util> git pull origin master --allow-unrelated-histories From * branch master -> FETCH_HEAD Merge made by the 'recursive' strategy. | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 ---->str-util> git push origin master fatal: HttpRequestException encountered. Error al enviar la solicitud. Username for '': YOUR_USER_NAME Password for '': Counting objects: 7, done. Delta compression using up to 4 threads. Compressing objects: 100% (4/4), done. Writing objects: 100% (7/7), 928 bytes | 309.00 KiB/s, done. Total 7 (delta 0), reused 0 (delta 0) To 16f9ce1..8f91cfa master -> master

Let’s analyze what we have done:

git init

Initialize the Git repository in our local directory. Git will create its hidden files to control operations made on the repository.

git add src

git add composer.json

We are telling Git which files we want to add to the repository. In our case only the src folder and the composer.json file will be synchronized, the rest of the files will stay only in our local machine.

git commit -m "Initial commit"

Our first Initial commit to our local instance of the repository. We haven’t sent anything to until now.

Now we will add an origin (origin means remote repository) to our local repository. This is the reference to our repository. Replace YOUR_USER_NAME with your own Github user name.

git remote add origin

If at this point we try to push (send to remote) the commit we made locally, an error will occur because in the remote instance of the repository there are files that don’t exist locally (README file for instance). We cannot send and receive at the same time under normal circumstances, so we will first pull files from origin ignoring possible conflicts:

git pull origin master --allow-unrelated-histories

Now, the README file is in our local repository as well. Now, we can push the commit we made before without any conflicts.

git push origin master

If we take a look to our Github repository, a new folder src should be created and inside it a file named Counter.php

Publishing part:

If everything went right, our package is available at Github and ready to be published on Packagist.

Log with your credentials (or using Github) into Packagist.

On the upper right corner, you will find a Submit button. Click on it and a new screen, titled “Submit package” will open.

Copy the URL of your Github repository and paste it inside the text box under “Repository URL (Git/Svn/Hg)”. Your URL should be something like this

Now press the big green button Check and if our package is OK, the button caption will change to Submit.

Press the Submit button and a new screen, showing the results will appear.

Our published package

Now you have a new package published in Packagist and anyone who wants to use it only has to type in its project folder:

composer require YOUR_USER_NAME/str-util

In a separate post, we will see how to include our new package in a project and invoke the test function we have created.

PHP: Send data to host over TCP/IP

Useful for single quick operations on a host (like sending a command)

 * Sends data over TCP/IP to the specified host
 * and returns host reply (limited to 1024 chars)
 * @param string $hostIP
 * @param int $hostPort
 * @param string $data
 * @return string
private function sendDataToHost(string $hostIP, int $hostPort, string $data){
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    $resp = "";
            socket_connect($socket, $hostIP, $hostPort);
            socket_write($socket, $data);
            $resp = socket_read($socket, 1024);
        }catch(\Exception $e){
            //Error while connecting socket
        //Error creating the socket
    return $resp;

Breadboard adapter for ESP32 dev. board

It is frustrating the first time you insert an ESP32 dev board into a breadboard and you notice there’s no room for wires.

ESP Dev Board on Breadboard
ESP Dev Board on Breadboard

What I usually do is putting a breadboard aside another one, but I don’t like it very much.

Workaround for ESP Dev Board on breadbord
Workaround for ESP Dev Board on two breadboards

I decided then to split the small board into two pieces and insert them in a 3D printed base so that the dev board pins get into the first row of holes and the rest remain available.

Splitted breadboard
Split breadboard
ESP32 Dev Board on split breadboard
ESP32 Dev Board on the split breadboard
Breadboard splitter design
Breadboard splitter

.stl file available at

Breadboard Splitter
Breadboard Splitter
Breadboard Splitter side view
Breadboard Splitter side view
Breadboard Splitter top view made my day

Since I was a child I loved gadgets, electronic parts, wires, opening every machine that fell into my hands.

My job is related to technology, but nothing of hardware in it, just software. I work for an advertising company and we don’t produce anything you can touch with your hands. Though I am an enthusiast of coding and designing software I am always buying cheap components, electrical instrumentation and from time to time I ‘produce’ some little things for the home, but I never have enough time to make interesting things. 

During years I have been reading blog entries at The things they talk about are those things I would love to be making the whole day.

Some months ago I started walking with pain in one of my feet. Things became more complicated and finally, I had surgery and had to stay at home during some months. That means a big issue for me because of my job but as someone said “problems can become opportunities” and that’s what it happened… now I have a bunch of time to think and study.

As I had a lot of components waiting for me, I decided to buy a 3D printer and make something. Three weeks ago I started thinking on an Alarm Clock and today that thing is Claudio.

Some days ago I submitted the Github repository link to thinking they would ignore it but they replied my email and told me their intention to publish a post about it. I felt really proud and happy. 

Today they made my day. Thanks, Tom! 😀

Hackaday post about Claudio

Claudio, the box

The box of the prototype consists of 4 pieces designed with Freecad to be 3D printed.

I used PLA, heating the bed up to 60ºC and the nozzle to 200ºC.

Claudio Front side
Frontside (from inside view)
Base (from inside view)
Cover (upside down)
Backside (from inside view)

Mounting is very simple and though the design includes eight blocks at the corners to allow screwing I found it wasn’t necessary as the pieces stay together after mounting due to pressure.

The four ‘columns’ at the base allow mounting a PCB over them and some wires can pass down it.

Some more pictures follow below:

Buzzer placement

DHT11 placement


MicroUSB hole
Mounted box


Claudio, parts and some links

Claudio consists of just five (or six) components, the wiring between them and code. No resistors, capacitors, diodes… no discrete components apart from 3 five cents of € coins. 😉

List of components:

  1. ESP32 Development Board: I’ve tested two different boards, and though they are very similar the results were not the same. 
    ESP32 Development Boards Front
    ESP32 Development Boards Front

    ESP32 Development Boards Back
    ESP32 Development Boards Back

    Price: US $7
    The first one was the one on the right side. It is a board I bought a year ago and it was working fine (for small tests) since then. When I first tried to put all the components together I noticed that ILI9341 TFT Display and WiFi connection were not good friends working at the same time. After 3 or 4 display operations (text, area fill, …) the screen went always blank and only when WiFi library was loaded. I tried multiple pin configurations, alternate libraries loading order. I tested voltage on each significant pin (D/C, CLOCK, MOSI) and no result.
    Finally, I decided to give a try one of the last boards I bought: the model on the left side. The result was successful. No blank screen. But, these boards have a bug design: they don’t allow uploading schemas directly from Arduino IDE (Error: Timed out waiting for packet header) and you have to ‘play’ with EN and BOOT buttons every time.
    Workaround: once Arduino IDE tries to upload the schema, press BOOT and without releasing it press also EN button, wait for a half second, release EN and when IDE stops waiting and starts the uploading you can release BOOT button.

    Error Time_out_waiting_for_packet_header
    Error uploading schema from Arduino IDE search for ESP32 Dev Board
  2. ILI9341TFT Screen – SPI
    Again, the component I had at home was about one year old. The only difference is that the one you can find now implements a set of pins to control a touch panel (though they say at the product description “non-touch”). Anyway, I think the one is being sold now is perfectly compatible with the previous model.
    What we need for this design is a model with an SPI pin configuration. Sellers usually refer to these as “driven with at least four IO”
    Price: US $7
    ILI9341 SPI TFT Display
    ILI9341 SPI TFT Display
     Sample link to ILI9341

  3. DHT-11 Temperature and Humidity Sensor
    This is a low-cost sensor very easy to use. Though it has four pins, only three of them have a function (the other one is not connected).
    Simply connect ground pin to GND, VCC pin to 3V3 and Data Out pin to any ESP32 IO pin.
    Depending on the range of temperature/humidity you need to measure, you should take a look also to DHT-22 sensor (which implements a wider range and more accuracy), but in my case, 0-50ºC/20-80%R.H. is quite enough.
    Price: US $1
    DHT-110 Temperature and Relative Humidity sensor link to DHT11 search

  4. BH1750FVI Digital Light Intensity Sensor
    I think the best feature of this sensor is, apart from ease of use, the sensibility and stability.
    It measures ambient light and gives the result in Lux
    It has 5 pins, but once again we can ignore one of them (ADD) by connecting it to GND. So, we only need two ESP32 IO pins to connect  SDA and SCL sensor pins.
    GND and VCC pins go to GND and 3V3 ESP32 pins respectively.
    Price: US $1
    BH1750FVI Ambient Light Sensor
    BH1750FVI Ambient Light Sensor link to BH1750FVI search

  5. Passive Piezo Buzzer
    The most basic part of the system.
    Just two pins (the middle one can be ignored), one goes to GND and the other one to an ESP32 IO pin.
    Price: US $0.2
    Passive Piezo Buzzer
    Passive Piezo Buzzer link to Piezo Buzzer search

  6. Touch sensors (5 cents of € coins)
    Each one connected to an ESP32 Touch pin.
    Price: 0.15€
    5 cents euro coin
    5 cents euro coin
    Mounted coin touch sensors
    Mounted coin touch sensors

ESP32 and ILI9341 ISP mode

After trying several options that I found on the web, I chose this one as the better to connect an ESP32 to an ILI9341 TFT display.

ESP32 ILI9341
D15 CS
D4 D/C
Not connected MISO
3V3 (***or D19) LED

The code:

 * ILI9341 TFT libraries and resources
const int TFT_CS = 15;
const int TFT_DC = 4;
const int TFT_MOSI = 23;
const int TFT_SLK = 18;
const int TFT_RST = 2;
const int TFT_LED = 19;     

#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_SLK, TFT_RST);

void setup() {
  tft.setRotation(3); //Landscape orientation

The reason for the two possibilities for the LED pin is the next:

If you connect LED pin directly to 3V3 you will get maximum brightness in your screen. LED pin controls the backlight of your TFT display.

In my case, I didn’t want to have max brightness but I wanted to control the intensity based on ambient light, so I decided to connect LED pin to any of the IO pins of the ESP32 (#19 in the showed example).

The code to control backlight intensity (once you have connected LED to pin D19) is as follows:

const int TFT_LED = 19; 
 * PWM Constants
const int freq = 5000;
const int tftledChannel = 0;
const int resolution = 8;
void setup() {
  //Background light PWM
  ledcSetup(tftledChannel, freq, resolution);
  ledcAttachPin(19, tftledChannel);

 * Sets TFT background luminosity (0-255)
void setBGLuminosity(int level){
  ledcWrite(tftledChannel, level);

Inserting the code above allows you to set the backlight intensity at any point just invoking setBGLuminosity() function passing a value between 0 and 255.


setBGLuminosity(0);   //Switch off screen backlight
setBGLuminosity(128); //Medium intensity (theoretically)
setBGLuminosity(255); //Full intensity

Claudio, available resources

Before going into detail of coding or wiring, I will publish here the links to the existing project resources (videos and code repositories).

Sorry about the video language, but I prefer writing in Spanish in places like youtube where automatic translation is good enough.

Youtube channel:

Github repositories:

Inside Hardware folder, you may find some hardware pictures and a wiring diagram (though this one will have its own post) and inside Box folder are the .obj files to 3d Print the box.