PHP without a framework

From Rixort Wiki
Revision as of 19:58, 15 March 2021 by Paul (Sọ̀rọ̀ | contribs)
Jump to navigation Jump to search

Things to think about

  • How to inject a request and eject a response.

Limitations

  • MySQL/MariaDB the only supported RDBMS.

Dependencies

The following dependencies are all actively maintained and available via Composer:

  • Dependency injection: PHP-DI
  • PSR-15 middleware dispatcher: Route
  • PSR-7 implementation: laminas-diactoros
  • Error handling: whoops
  • Templates: Twig
  • Logging: monolog/monolog
  • Date/Time manipulation: nesbot/carbon

For configuration variables, use a simple PHP script which returns an array and is brought in using require_once. This should work across all versions of PHP and if anyone accesses the file directly they will be shown a blank page (but it is still a good idea to keep it outside the document root and not in version control).

Databases

Use PDO for everything, as this gives the maximum flexibility.

  • Set the charset in the DSN.

PHP built-in server

The PHP built-in server is sufficient for most purposes. Create a configuration file, local.ini:

error_reporting = E_ALL
display_errors = On

Start the server:

php -S localhost:8000 -t public -c local.ini

Instructions

Initialise composer project

composer init

Add dependencies

composer require php-di/php-di
composer require filp/whoops
composer require relay/relay
composer require laminas/laminas-diactoros
composer require league/route

Create skeleton directory structure:

mkdir public sr

Bootstrap file

Create Bootstrap file at src/Bootstrap.php:

<?php

declare(strict_types = 1);
error_reporting(E_ALL);

date_default_timezone_set('Europe/London');

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

$whoops = new Whoops\Run;
$whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
$whoops->register();

Front controller

Create skeleton front controller at public/index.php:

<?php

declare(strict_types = 1);

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

Create HelloWorld class in src/HelloWorld.php:

<?php

declare(strict_types = 1);

namespace MyApp;

class HelloWorld
{
  public function hello() : void
  {
    echo 'Hello World';
  }
}

Logins and registration

  • password_hash
  • password_verify
  • password_needs_rehash