Alight is a light-weight PHP framework. Easily and quickly build high performance RESTful web applications. Out-of-the-box built-in routing, database, caching, error handling, logging and job scheduling libraries. Focus on creating solutions for the core process of web applications. Keep simple and extensible.
| Project | Description |
|---|---|
| Alight | Basic framework built-in routing, database, caching, etc. |
| Alight-Admin | A full admin panel extension based on Alight. No front-end coding required. |
| Alight-Project | A template for beginner to easily create web applications by Alight/Alight-Admin. |
PHP 7.4+
Don’t have Composer? Install Composer first.
$ composer create-project juneszh/alight-project {PROJECT_DIRECTORY}The project template contains common folder structure, suitable for MVC pattern, please refer to: Alight-Project.
It is easy to customize folders by modifying the configuration. But the following tutorials are based on the template configuration.
Nginx example (Nginx 1.17.10, PHP 7.4.3, Ubuntu 20.04.3):
server {
listen 80;
listen [::]:80;
root /var/www/{PROJECT_DIRECTORY}/public;
index index.php;
server_name {YOUR_DOMAIN};
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ .php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
}All of the configuration options for the Alight framework will be imported from the file 'config/app.php', which you need to create yourself. For example:
File: config/app.php
<?php
return [
'app' => [
'debug' => false,
'timezone' => 'Europe/Kiev',
'storagePath' => 'storage',
'domainLevel' => 2,
'corsDomain' => null,
'corsHeaders' => null,
'corsMethods' => null,
'cacheAdapter' => null,
'errorHandler' => null,
'errorPageHandler' => null,
],
'route' => 'config/route/web.php',
'database' => [
'type' => 'mysql',
'host' => '127.0.0.1',
'database' => 'alight',
'username' => 'root',
'password' => '',
],
'cache' => [
'type' => 'file',
],
'job' => 'config/job.php',
];<?php
AlightConfig::get('app');
AlightConfig::get('app', 'storagePath');See Config.php for details.
Before learning routing rules, you need to create a php file first that stores routing rules. Because the routing cache is updated or not, it is based on the modification time of the routing file. For example:
File: config/route/web.php
AlightRoute::get('/', 'Controller::index');File: config/app.php
<?php
return [
'route' => 'config/route/web.php'
// Also supports multiple files
// 'route' => ['config/route/web.php', config/route/api.php']
];By the way, the route configuration supports importing specified files for subdomains:
<?php
return [
'route' => [
//Import on any request
'*' => 'config/route/web.php',
//Import when requesting admin.yourdomain.com
'admin' => 'config/route/admin.php',
//Import multiple files when requesting api.yourdomain.com
'api' => ['config/route/api.php', 'config/route/api_mobile.php'],
]
];AlightRoute::get($pattern, $handler);
// Example
AlightRoute::get('/', 'Controller::index');
AlightRoute::get('/', ['Controller', 'index']);
// Or try this to easy trigger hints from IDE
AlightRoute::get('/', [Controller::class, 'index']);
// With default args
AlightRoute::get('post/list[/{page}]', [Controller::class, 'list'], ['page' => 1]);
// Common HTTP request methods
AlightRoute::options('/', 'handler');
AlightRoute::head('/', 'handler');
AlightRoute::post('/', 'handler');
AlightRoute::delete('/', 'handler');
AlightRoute::put('/', 'handler');
AlightRoute::patch('/', 'handler');
// Map for Custom methods
AlightRoute::map(['GET', 'POST'], 'test', 'handler');
// Any for all common methods
AlightRoute::any('test', 'handler');// Matches /user/42, but not /user/xyz
AlightRoute::get('user/{id:d+}', 'handler');
// Matches /user/foobar, but not /user/foo/bar
AlightRoute::get('user/{name}', 'handler');
// Matches /user/foo/bar as well, using wildcards
AlightRoute::get('user/{name:.+}', 'handler');
// The /{name} suffix is optional
AlightRoute::get('user[/{name}]', 'handler');
// Root wildcards for single page app
AlightRoute::get('/{path:.*}', 'handler');nikic/fast-route handles all regular expressions in the routing path. See FastRoute Usage for details.
AlightRoute::group('admin');
// Matches /admin/role/list
AlightRoute::get('role/list', 'handler');
// Matches /admin/role/info
AlightRoute::get('role/info', 'handler');
// Override the group
AlightRoute::group('api');
// Matches /api/news/list
AlightRoute::get('news/list', 'handler');You can customize the methods contained in AlightRoute::any().
AlightRoute::setAnyMethods(['GET', 'POST']);
AlightRoute::any('only/get/and/post', 'handler');If you want to run some common code before route's handler.
// For example log every hit request
AlightRoute::beforeHandler([svcRequest::class, 'log']);
AlightRoute::get('test', 'handler');
AlightRoute::post('test', 'handler');Not recommended, but if your code requires:
// Effective in the current route file
AlightRoute::disableCache();All routing options only take effect in the current file and will be auto reset by AlightRoute::init() before the next file is imported. For example:
File: config/admin.php
AlightRoute::group('admin');
AlightRoute::setAnyMethods(['GET', 'POST']);
// Matches '/admin/login' by methods 'GET', 'POST'
AlightRoute::any('login', 'handler');File: config/web.php
// Matches '/login' by methods 'GET', 'POST', 'PUT', 'DELETE', etc
AlightRoute::any('login', 'handler');Send a Cache-Control header to control caching in browsers and shared caches (CDN) in order to optimize the speed of access to unmodified data.
// Cache one day
AlightRoute::get('about/us', 'handler')->cache(86400);
// Or force disable cache
AlightRoute::put('user/info', 'handler')->cache(0);We provide a simple authorization handler to manage user login status.
// Define a global authorization verification handler
AlightRoute::authHandler([svcAuth::class, 'verify']);
// Enable verification in routes
AlightRoute::get('user/info', 'handler')->auth();
AlightRoute::get('user/password', 'handler')->auth();
// No verification by default
AlightRoute::get('about/us', 'handler');
// In general, routing with authorization will not use browser cache
// So auth() has built-in cache(0) to force disable cache
// Please add cache(n) after auth() to override the configuration if you need
AlightRoute::get('user/rank/list', 'handler')->auth()->cache(3600);File: app/service/Auth.php
namespace svc;
class Auth
{
public static function verify()
{
// Some codes about get user session from cookie or anywhere
// Returns the user id if authorization is valid
// Otherwise returns 0 or something else for failure
// Then use Router::getAuthId() in the route handler to get this id again
return $userId;
}
}Many times the data submitted by the user takes time to process, and we don't want to receive the same data before it's processed. So we need to set the request cooldown time. The user will receive a 429 error when requesting again within the cooldown.
// Cooldown only takes effect when authorized
AlightRoute::put('user/info', 'handler')->auth()->cd(2);
AlightRoute::post('user/status', 'handler')->auth()->cd(2);When your API needs to be used for Ajax requests by a third-party website (or your project has multiple domains), you need to send a set of CORS headers. For specific reasons, please refer to: Mozilla docs.
// Domains in config will receive the common cors header
AlightRoute::put('share/config', 'handler')->cors();
// The specified domain will receive the common cors header
AlightRoute::put('share/specified', 'handler')->cors('abc.com');
// The specified domain will receive the specified cors header
AlightRoute::put('share/specified2', 'handler')->cors('abc.com', 'Authorization', ['GET', 'POST']);
// All domains will receive a 'Access-Control-Allow-Origin: *' header
AlightRoute::put('share/all/http', 'handler')->cors('*');
// All domains will receive a 'Access-Control-Allow-Origin: [From Origin]' header
AlightRoute::put('share/all/https', 'handler')->cors('origin');If your website is using CDN, please use this utility carefully. To avoid request failure after the header is cached by CDN.
Alight passes the 'database' configuration to the catfan/medoo directly. For specific configuration options, please refer to Medoo Get Started. For example:
File: config/app.php
<?php
return [
'database' => [
'type' => 'mysql',
'host' => '127.0.0.1',
'database' => 'alight',
'username' => 'root',
'password' => '',
],
// Multiple databases (The first database is default)
// 'database' => [
// 'main' => [
// 'type' => 'mysql',
// 'host' => '127.0.0.1',
// 'database' => 'alight',
// 'username' => 'root',
// 'password' => '',
// ],
// 'remote' => [
// 'type' => 'mysql',
// 'host' => '1.1.1.1',
// 'database' => 'alight',
// 'username' => 'root',
// 'password' => '',
// ],
// ]
];AlightDatabase::init() is a static and single instance implementation of new MedooMedoo(), so it inherits all functions of Medoo(). Single instance makes each request connect to the database only once and reuse it, effectively reducing the number of database connections.
// Initializes the default database
$db = AlightDatabase::init();
// Initializes others database with key
$db2 = AlightDatabase::init('remote');
$userList = $db->select('user', '*', ['role' => 1]);
$userInfo = $db->get('user', '*', ['id' => 1]);
$db->insert('user', ['name' => 'anonymous', 'role' => 2]);
$id = $db->id();
$result = $db->update('user', ['name' => 'alight'], ['id' => $id]);
$result->rowCount();See Medoo Documentation for usage details.
Alight supports multiple cache drivers and multiple cache interfaces with symfony/cache. The configuration options 'dsn' and 'options' will be passed to the cache adapter, more details please refer to Available Cache Adapters. For example:
File: config/app.php
<?php
return [
'cache' => [
'type' => 'file',
],
// Multiple cache (The first cache is the default)
// 'cache' => [
// 'file' => [
// 'type' => 'file',
// ],
// 'memcached' => [
// 'type' => 'memcached',
// 'dsn' => 'memcached://localhost',
// 'options' => [],
// ],
// 'redis' => [
// 'type' => 'redis',
// 'dsn' => 'redis://localhost',
// 'options' => [],
// ],
// ]
];Like database, AlightCache::init() is a static and single instance implementation of the cache client to improve concurrent request performance.
// Initializes the default cache
$cache = AlightCache::init();
// Initializes others cache with key
$cache2 = AlightCache::init('redis');
// Use SimpleCache(PSR-16) interface
if (!$cache->has('test')){
$cache->set('test', 'hello world!', 3600);
}
$cacheData = $cache->get('test');
$cache->delete('test');$cache6 = AlightCache::psr6('memcached');
$cacheItem = $cache6->getItem('test');
if (!$cacheItem->isHit()){
$cacheItem->expiresAfter(3600);
$cacheItem->set('hello world!');
// Bind to a tag
$cacheItem->tag('alight');
}
$cacheData = $cacheItem->get();
$cache6->deleteItem('test');
// Delete all cached items in the same tag
$cache6->invalidateTags('alight')
// Or symfony/cache adapter style
$cacheData = $cache6->get('test', function ($item){
$item->expiresAfter(3600);
return 'hello world!';
});
$cache6->delete('test');Also supports memcached or redis native interfaces for using advanced caching:
$memcached = AlightCache::memcached('memcached');
$memcached->increment('increment');
$redis = AlightCache::redis('redis');
$redis->lPush('list', 'first');symfony/cache supports more than 10 adapters, but we only have built-in 3 commonly used, such as filesystem, memcached, redis. If you need more adapters, you can expand it. For example:
File: config/app.php
<?php
return [
'app' => [
'cacheAdapter' => [svcCache::class, 'adapter'],
],
'cache' => [
// ...
'apcu' => [
'type' => 'apcu'
],
'array' => [
'type' => 'array',
'defaultLifetime' => 3600
]
]
];File: app/service/Cache.php
namespace svc;
use SymfonyComponentCacheAdapterApcuAdapter;
use SymfonyComponentCacheAdapterArrayAdapter;
use SymfonyComponentCacheAdapterNullAdapter;
class Cache
{
public static function adapter(array $config)
{
switch ($config['type']) {
case 'apcu':
return new ApcuAdapter();
break;
case 'array':
return new ArrayAdapter($config['defaultLifetime']);
default:
return new NullAdapter();
break;
}
}
}See Symfony Cache Component for more information.
Alight catches all errors via AlightApp::start(). When turn on 'debug' in the app configuration, errors will be output in pretty html (by filp/whoops) or JSON.
File: config/app.php
<?php
return [
'app' => [
'debug' => true,
]
];When turn off 'debug' in production environment, Alight just logs errors to file and outputs HTTP status. You can override these default behaviors by app configuration. For example:
File: config/app.php
<?php
return [
'app' => [
'errorHandler' => [svcError::class, 'catch'],
'errorPageHandler' => [svcError::class, 'page'],
]
];File: app/service/Error.php
namespace svc;
class Error
{
public static function catch(Throwable $exception)
{
// Some code like sending an email or using Sentry or something
}
public static function page(int $status)
{
switch ($status) {
case 400:
// Page code...
break;
case 401:
// Page code...
break;
case 403:
// Page code...
break;
case 404:
// Page code...
break;
case 500:
// Page code...
break;
default:
// Page code...
break;
}
}
}If you need to run php scripts in the background periodically.
$ sudo contab -eAdd the following to the end line:
* * * * * sudo -u www-data /usr/bin/php /var/www/{PROJECT_DIRECTORY}/app/scheduler.php >> /dev/null 2>&1File: config/job.php
AlightJob::call('handler')->minutely();
AlightJob::call('handler')->hourly();
AlightJob::call('handler')->daily();
AlightJob::call('handler')->weekly();
AlightJob::call('handler')->monthly();
AlightJob::call('handler')->yearly();
AlightJob::call('handler')->everyMinutes(5);
AlightJob::call('handler')->everyHours(2);
AlightJob::call('handler')->date('2022-08-02 22:00');Each handler runs only one process at a time, and the default max runtime of a process is 1 hour. If your handler needs a longer runtime, use timeLimit().
AlightJob::call('handler')->hourly()->timeLimit(7200);// 7200 secondsAlight provides AlightApp::root() to standardize the format of file paths in project.
// Suppose the absolute path of the project is /var/www/my_project/
AlightApp::root('public/favicon.ico'); // /var/www/my_project/public/favicon.ico
// Of course, you can also use absolute path files with the first character '/'
AlightApp::root('/var/data/config/web.php');The file paths in the configuration are all based on the AlightApp::root(). For example:
AlightApp::start([
'route' => 'config/route/web.php', // /var/www/my_project/config/route/web.php
'job' => 'config/job.php' // /var/www/my_project/config/job.php
]);Alight provides AlightResponse::api() to standardize the format of API Response.
HTTP 200 OK
{
"error": 0, // API error code
"message": "OK", // API status description
"data": {} // Object data
}Status Definition:
| HTTP Status | API Error | Description |
|---|---|---|
| 200 | 0 | OK |
| 200 | 1xxx | General business errors, only display message to user |
| 200 | 2xxx | Special business errors, need to define next action for user |
| 4xx | 4xx | Client errors |
| 5xx | 5xx | Server errors |
For example:
AlightResponse::api(0, null, ['name' => 'alight']);
// Response:
// HTTP 200 OK
//
// {
// "error": 0,
// "message": "OK",
// "data": {
// "name": "alight"
// }
// }
AlightResponse::api(1001, 'Invalid request parameter.');
// Response:
// HTTP 200 OK
//
// {
// "error": 1001,
// "message": "Invalid request parameter.",
// "data": {}
// }
AlightResponse::api(500, 'Unable to connect database.');
// Response:
// HTTP 500 Internal Server Error
//
// {
// "error": 500,
// "message": "Unable to connect database.",
// "data": {}
// }Alight provides AlightResponse::render() to display a view template call the render method with the path of the template file and optional template data:
File: app/controller/Pages.php
namespace ctr;
class Pages
{
public static function index()
{
AlightResponse::render('hello.php', ['name' => 'Ben']);
}
}File: app/view/hello.php
<h1>Hello, <?= $name ?>!</h1>File: config/route/web.php
AlightRoute::get('/', [ctrPages::class, 'index']);The project's homepage output would be:
Hello, Ben!There are also some useful helpers placed in different namespaces. Please click the file for details:
| Namespace | File |
|---|---|
| AlightRequest | Request.php |
| AlightResponse | Response.php |
| AlightUtility | Utility.php |