My PHP Toolkit to Build a (quite) Frameworkless App

Boris Jamot ✊ / - Jan 22 '19 - - Dev Community

Hey, let me introduce you some of the libraries & tools I've been using in many PHP projects running in production.

I'm used to build my own framework by picking up libs in the below list each time I start a new PHP project. But to be honest, I must admit that I still use a micro-framework for basic HTTP stuff: Slim.

πŸ“ I use no ORM and I mainly build backend apps with Web APIs.

Libraries

1. Slim Framework

slim

πŸ™‹ Purpose: Micro-Framework intended to build Web APIs
🌠 GitHub stars: 9,475
πŸ”— URL: slimphp/slim

2. Slim Framework CSRF protection middleware

GitHub logo slimphp / Slim-Csrf

Slim Framework CSRF protection middleware

Slim Framework CSRF Protection

Build Status Coverage Status

This repository contains a Slim Framework CSRF protection PSR-15 middleware. CSRF protection applies to all unsafe HTTP requests (POST, PUT, DELETE, PATCH).

You can fetch the latest CSRF token's name and value from the Request object with its getAttribute() method. By default, the CSRF token's name is stored in the csrf_name attribute, and the CSRF token's value is stored in the csrf_value attribute.

Install

Via Composer

$ composer require slim/csrf
Enter fullscreen mode Exit fullscreen mode

Requires Slim 4.0.0 or newer.

Usage

In most cases you want to register Slim\Csrf for all routes, however, as it is middleware, you can also register it for a subset of routes.

Register for all routes

use DI\Container
use Slim\Csrf\Guard;
use Slim\Factory\AppFactory;

require __DIR__ . '/vendor/autoload.php';

// Start PHP session
session_start();

// Create Container
$container = new Container();
AppFactory::
…
Enter fullscreen mode Exit fullscreen mode

πŸ™‹ Purpose: Protect your GUI pages with a CSRF token
🌠 GitHub stars: 201
πŸ”— URL: slimphp/csrf

3. Slim Framework Flash Messages

GitHub logo slimphp / Slim-Flash

Slim Framework flash messages service provider

Slim Framework Flash Messages

Build Status

This repository contains a Slim Framework Flash messages service provider. This enables you to define transient messages that persist only from the current request to the next request.

Install

Via Composer

$ composer require slim/flash
Enter fullscreen mode Exit fullscreen mode

Requires Slim 3.0.0 or newer.

Usage

Slim 4

This example assumes that you have php-di/php-di installed.

<?php
use DI\ContainerBuilder;
use Slim\Factory\AppFactory;
use Slim\Flash\Messages;
use Slim\Routing\RouteContext;

require_once __DIR__ . '/../vendor/autoload.php';

$containerBuilder = new ContainerBuilder();

// Add container definition for the flash component
$containerBuilder->addDefinitions(
    [
        'flash' => function () {
            $storage = [];
            return new Messages($storage);
        }
    ]
);

AppFactory::setContainer($containerBuilder->build());

$app = AppFactory::create();

// Add session start middleware
$app->
…
Enter fullscreen mode Exit fullscreen mode

πŸ™‹ Purpose: This enables you to define transient messages that persist only from the current request to the next request
🌠 GitHub stars: 104
πŸ”— URL: slimphp/flash

4. Twig

twig

πŸ™‹ Purpose: A very popular template engine that integrates well with Slim (slimphp/twig-view)
🌠 GitHub stars: 5,705
πŸ”— URL: twigphp/twig

5. Monolog

GitHub logo Seldaek / monolog

Sends your logs to files, sockets, inboxes, databases and various web services

Monolog

Monolog - Logging for PHP Continuous Integration

Total Downloads Latest Stable Version

Note This is the documentation for Monolog 3.x, if you are using older releases see the documentation for Monolog 2.x or Monolog 1.x

Monolog sends your logs to files, sockets, inboxes, databases and various web services. See the complete list of handlers below. Special handlers allow you to build advanced logging strategies.

This library implements the PSR-3 interface that you can type-hint against in your own libraries to keep a maximum of interoperability. You can also use it in your applications to make sure you can always use another compatible logger at a later time As of 1.11.0 Monolog public APIs will also accept PSR-3 log levels Internally Monolog still uses its own level scheme since it predates PSR-3.

Installation

Install the latest version with

composer require monolog/monolog
Enter fullscreen mode Exit fullscreen mode

Basic Usage

<?php
use
…
Enter fullscreen mode Exit fullscreen mode

πŸ™‹ Purpose: Sends your logs to files, sockets, inboxes, databases and various web services
🌠 GitHub stars: 13,388
πŸ”— URL: seldaek/monolog

6. Zend ACL permissions




πŸ™‹ Purpose: Provides a lightweight and flexible access control list (ACL) implementation for privileges management
🌠 GitHub stars: 55
πŸ”— URL: zendframework/zend-permissions-acl

7. Guzzle

GitHub logo guzzle / guzzle

Guzzle, an extensible PHP HTTP client

Guzzle

Guzzle, PHP HTTP client

Latest Version Build Status Total Downloads

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.

  • Simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data etc...
  • Can send both synchronous and asynchronous requests using the same interface.
  • Uses PSR-7 interfaces for requests, responses, and streams. This allows you to utilize other PSR-7 compatible libraries with Guzzle.
  • Supports PSR-18 allowing interoperability between other PSR-18 HTTP Clients.
  • Abstracts away the underlying HTTP transport, allowing you to write environment and transport agnostic code; i.e., no hard dependency on cURL PHP streams, sockets, or non-blocking event loops.
  • Middleware system allows you to augment and compose client behavior.
$client = new \GuzzleHttp\Client()
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');

echo $response->getStatusCode(); 
…
Enter fullscreen mode Exit fullscreen mode

πŸ™‹ Purpose: Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services
🌠 GitHub stars: 15,355
πŸ”— URL: guzzlehttp/guzzle

8. PDO

πŸ™‹ Purpose: PHP extension to build and execute secured SQL prepared statements
πŸ”— URL: PDO

9. Zend XML-RPC

GitHub logo zendframework / zend-xmlrpc

XmlRpc component from Zend Framework

zend-xmlrpc

Repository abandoned 2019-12-31

This repository has moved to laminas/laminas-xmlrpc.

Build Status Coverage Status

From its home page, XML-RPC is described as a ”...remote procedure calling using HTTP as the transport and XML as the encoding. XML-RPC is designed to be as simple as possible, while allowing complex data structures to be transmitted, processed and returned.”

Zend\XmlRpc provides support for both consuming remote XML-RPC services and building new XML-RPC servers.




πŸ™‹ Purpose: Provides support for both consuming remote XML-RPC services and building new XML-RPC servers
🌠 GitHub stars: 14
πŸ”— URL: zendframework/zend-xmlrpc

10. PHPMailer

GitHub logo PHPMailer / PHPMailer

The classic email sending library for PHP

SWUbanner

PHPMailer

PHPMailer – A full-featured email creation and transfer class for PHP

Test status codecov.io Latest Stable Version Total Downloads License API Docs OpenSSF Scorecard

Features

  • Probably the world's most popular code for sending email from PHP!
  • Used by many open-source projects: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla! and many more
  • Integrated SMTP support – send without a local mail server
  • Send emails with multiple To, CC, BCC, and Reply-to addresses
  • Multipart/alternative emails for mail clients that do not read HTML email
  • Add attachments, including inline
  • Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings
  • SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SMTPS and SMTP+STARTTLS transports
  • Validates email addresses automatically
  • Protects against header injection attacks
  • Error messages in over 50 languages!
  • DKIM and S/MIME signing support
  • Compatible with PHP 5.5 and later, including PHP 8.2
  • Namespaced to prevent name clashes
  • Much more!

Why you might need it

Many PHP developers need to send email from their code. The only…

πŸ™‹ Purpose: A full-featured email creation and transfer class for PHP
🌠 GitHub stars: 12,422
πŸ”— URL: phpmailer/phpmailer

11. Firebase / PHP-JWT

GitHub logo firebase / php-jwt

PHP package for JWT

Build Status Latest Stable Version Total Downloads License

PHP-JWT

A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to RFC 7519.

Installation

Use composer to manage your dependencies and download PHP-JWT:

composer require firebase/php-jwt
Enter fullscreen mode Exit fullscreen mode

Optionally, install the paragonie/sodium_compat package from composer if your php env does not have libsodium installed:

composer require paragonie/sodium_compat
Enter fullscreen mode Exit fullscreen mode

Example

use Firebase\JWT\JWT
use Firebase\JWT\Key;

$key = 'example_key';
$payload = [
    'iss' => 'http://example.org',
    'aud' => 'http://example.com',
    'iat' => 1356999524,
    'nbf' => 1357000000
];

/**
 * IMPORTANT:
 * You must specify supported algorithms for your application. See
 * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
 * for a list of spec-compliant algorithms.
 */
$jwt = JWT::encode($payload, $key, 'HS256');
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
print_r($decoded
…
Enter fullscreen mode Exit fullscreen mode

πŸ™‹ Purpose: A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to RFC 7519
🌠 GitHub stars: 4,574
πŸ”— URL: firebase/php-jwt

12. Hassankhan / Config

GitHub logo hassankhan / config

Config is a lightweight configuration file loader that supports PHP, INI, XML, JSON, and YAML files

Config

Latest version Software License Build Status Coverage Status Quality Score Total Downloads Gitter

Config is a file configuration loader that supports PHP, INI, XML, JSON YML, Properties and serialized files and strings.

Requirements

Config requires PHP 7.4+.

IMPORTANT: If you want to use YAML files or strings, require the Symfony Yaml component in your composer.json.

Installation

The supported way of installing Config is via Composer.

$ composer require hassankhan/config
Enter fullscreen mode Exit fullscreen mode

Usage

Config is designed to be very simple and straightforward to use. All you can do with it is load, get, and set.

Loading files

The Config object can be created via the factory method load(), or by direct instantiation:

use Noodlehaus\Config
use Noodlehaus\Parser\Json;

// Load a single file
$conf = Config::load('config.json');
$conf = new Config('config.json');

// Load values from multiple files
$conf = new Config(['config.json', 'config.xml']);

//
…
Enter fullscreen mode Exit fullscreen mode

πŸ™‹ Purpose: Config is a lightweight configuration file loader that supports PHP, INI, XML, JSON, and YAML files
🌠 GitHub stars: 749
πŸ”— URL: hassankhan/config

Tools

As a PHP craftsman, the tools below are mandatory in my toolkit. Most of them (except shellcheck) are installable through composer, which allows you to add them as dev dependencies to your project's composer.json.

1. Composer

composer

πŸ™‹ Purpose: Essential PHP dependency manager, and much more
🌠 GitHub stars: 18,049
πŸ”— URL: Composer

2. PHPUnit

phpunit

πŸ™‹ Purpose: Awesome unit tests framework with mocking features
🌠 GitHub stars: 12,785
πŸ”— URL: PHPUnit

3. PHP Code Sniffer

GitHub logo squizlabs / PHP_CodeSniffer

PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.

Warning

This repository has been abandoned. Its successor is PHPCSStandards/PHP_CodeSniffer

See issue #3932 for more information.

About

PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.

Build Status Build Status Code consistency Join the chat at https://gitter.im/squizlabs/PHP_CodeSniffer

Requirements

PHP_CodeSniffer requires PHP version 5.4.0 or greater, although individual sniffs may have additional requirements such as external applications and scripts. See the Configuration Options manual page for a list of these requirements.

If you're using PHP_CodeSniffer as part of a team, or you're running it on a CI server, you may want to configure your project's settings using a configuration file.

Installation

The easiest way to get started with PHP_CodeSniffer is to download the Phar files for each of…

πŸ™‹ Purpose: Static analysis tool to detect & fix coding standard violations
🌠 GitHub stars: 5,915
πŸ”— URL: squizlabs/php_codesniffer

4. PHP Mess Detector aka phpmd

phpmd

πŸ™‹ Purpose: Static analysis tool to detect code smells, bad design, bugs, unused parameters, etc.
🌠 GitHub stars: 1,315
πŸ”— URL: phpmd/phpmd

5. PHP Coding Standard Fixer aka php-cs-fixer

php-cs-fixer

πŸ™‹ Purpose: Automatically fixes coding standard violations
🌠 GitHub stars: 7,036
πŸ”— URL: friendsofphp/php-cs-fixer

6. SensioLabs Security Checker

security-checker

πŸ™‹ Purpose: The SensioLabs Security Checker is a command line tool that checks if your application uses dependencies with known security vulnerabilities
🌠 GitHub stars: 1,397
πŸ”— URL: sensiolabs/security-checker

7. XML Linter

GitHub logo sclable / xml-lint

A php tool to lint and validate xml files from the commandline.

Sclable XML Lint

A php tool to lint and validate xml files from the commandline.

Build Status Latest Stable Version Total Downloads License

XML Lint checks the syntax of any xml files and validates the file against the XSD schema defined in the file.

Usage

Installation with Composer

If you'd like to include this library in your project with composer, simply run:

composer require "sclable/xml-lint"

Command Line Usage

To lint a single xml file:

vendor/bin/xmllint path/to/file.xml

To lint a directory and all its subdirectories:

vendor/bin/xmllint path/to/dir

Help

xmllint has built in cli help screen:

vendor/bin/xmllint --help

Options

  • -v be verbose, display the filename of the current file to lint
  • -r 0 don't search recursive (if the argument is a directory)
  • -e name exclude files or directories containing 'name'
  • -s skip the xsd validation

Development

Run tests

# check code style
php tools/php-cs-fixer/vendor/bin/php-cs-fixer fix --dry-run -v

# run tests
php vendor/bin/phpunit
php vendor/bin/behat
Enter fullscreen mode Exit fullscreen mode

Using docker:

# Example
docker
…
Enter fullscreen mode Exit fullscreen mode

πŸ™‹ Purpose: A PHP tool to lint and validate XML files from the command line
🌠 GitHub stars: 6
πŸ”— URL: sclable/xml-lint

8. YAML Linter

GitHub logo j13k / yaml-lint

A compact command line linting tool for validating YAML files.

yaml-lint

Latest Version on Packagist Software License Total Downloads Monthly Downloads CI

A compact command line linting tool for validating YAML files, using the parsing facility of the Symfony Yaml Component.

Usage

usage: yaml-lint [options] [input source]

  input source    Path to file(s), or "-" to read from standard input

  -q, --quiet     Restrict output to syntax errors
  -h, --help      Display this help
  -V, --version   Display application version

Install

Composer

To get started using yaml-lint in a project, install it with Composer:

composer require --dev j13k/yaml-lint
Enter fullscreen mode Exit fullscreen mode

It can then be run from the project's vendor/bin directory.

To set up yaml-lint globally, install it in the Composer home directory:

composer global require j13k/yaml-lint
Enter fullscreen mode Exit fullscreen mode

It can then be run from the bin directory of Composer home (typically ~/.composer/vendor/bin).

Binary

A binary edition , yaml-lint.phar, is available for download with each release. This embeds the latest stable version of the Symfony Yaml component that is current at the time of the release.

…

πŸ™‹ Purpose: Compact command line utility for checking YAML file syntax
🌠 GitHub stars: 3
πŸ”— URL: j13k/yaml-lint

9. Dockerfile Linter

NPM Build Status

dockerfile-lint

A rule based 'linter' for Dockerfiles. The linter rules can be used to check file syntax as well as arbitrary semantic and best practice attributes determined by the rule file writer The linter can also be used to check LABEL rules against docker images.

Table of Contents

Quickstart

  1. Change to directory where you have a Dockerfile
  2. run
  • Atomic CLI

        atomic run projectatomic/dockerfile-lint
    
        atomic run projectatomic/dockerfile-lint image <imageid>
    
  • Docker CLI

        docker run -it --rm -v $PWD:/root/ \
               projectatomic/dockerfile-lint \
               dockerfile_lint [-f Dockerfile]
    
        docker run -it --rm -v $PWD:/root/  \
               -v /var/run/docker.sock:/var/run/docker.sock \
               projectatomic/dockerfile-lint \
               dockerfile_lint  image <imageid>
    

By default, the linter runs in strict mode (errors and/or warnings result in non-zero return code). Run the command with -p or --permissive to…

πŸ™‹ Purpose: Rule based Dockerfile linter
🌠 GitHub stars: 259
πŸ”— URL: projectatomic/dockerfile_lint

10. Shellcheck

GitHub logo koalaman / shellcheck

ShellCheck, a static analysis tool for shell scripts

Build Status

ShellCheck - A shell script static analysis tool

ShellCheck is a GPLv3 tool that gives warnings and suggestions for bash/sh shell scripts:

Screenshot of a terminal showing problematic shell script lines highlighted

The goals of ShellCheck are

  • To point out and clarify typical beginner's syntax issues that cause a shell to give cryptic error messages.

  • To point out and clarify typical intermediate level semantic problems that cause a shell to behave strangely and counter-intuitively.

  • To point out subtle caveats, corner cases and pitfalls that may cause an advanced user's otherwise working script to fail under future circumstances.

See the gallery of bad code for examples of what ShellCheck can help you identify!

Table of Contents

πŸ™‹ Purpose: A static analysis tool for shell scripts
🌠 GitHub stars: 13,440
πŸ”— URL: koalaman/shellcheck

11. Swagger CLI

swagger-cli

πŸ™‹ Purpose: Validate Swagger/OpenAPI files in JSON or YAML format
🌠 GitHub stars: 125
πŸ”— URL: APIDevTools/swagger-cli


All these tools can be run automatically:

  • in your IDE
  • in a git hook
  • in your CI/CD pipeline

If you want to go further, please have a look at one of my former articles:

Thanks for reading.

See ya!

. . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player