降車は軽量のPHPフレームワークです。高性能のRestful Webアプリケーションを簡単かつ迅速に構築します。すぐに組み込まれた内蔵ルーティング、データベース、キャッシュ、エラー処理、ロギング、ジョブスケジューリングライブラリ。 Webアプリケーションのコアプロセスのソリューションの作成に焦点を当てます。シンプルで拡張可能にしてください。
| プロジェクト | 説明 |
|---|---|
| 降りる | 基本的なフレームワーク内蔵ルーティング、データベース、キャッシュなど。 |
| aight-admin | 発光に基づく完全な管理パネル拡張機能。フロントエンドコーディングは必要ありません。 |
| aight-project | 初心者向けのテンプレートは、light/light-adminによってWebアプリケーションを簡単に作成できます。 |
PHP 7.4+
作曲家がいませんか?最初に作曲家をインストールします。
$ composer create-project juneszh/alight-project {PROJECT_DIRECTORY}プロジェクトテンプレートには、MVCパターンに適した共通のフォルダー構造が含まれています。
構成を変更することで、フォルダーをカスタマイズするのは簡単です。ただし、次のチュートリアルはテンプレート構成に基づいています。
Nginxの例(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;
}
}[Framework]のすべての構成オプションは、ファイル「config/app.php」からインポートされます。これを作成する必要があります。例えば:
ファイル: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
Alight Config:: get ( ' app ' );
Alight Config:: get ( ' app ' , ' storagePath ' );詳細については、config.phpを参照してください。
ルーティングルールを学習する前に、ルーティングルールを保存するPHPファイルを最初に作成する必要があります。ルーティングキャッシュが更新されるかどうかは、ルーティングファイルの変更時間に基づいています。例えば:
ファイル:config/route/web.php
Alight Route:: get ( ' / ' , ' Controller::index ' );ファイル:config/app.php
<?php
return [
' route ' => ' config/route/web.php '
// Also supports multiple files
// 'route' => ['config/route/web.php', config/route/api.php']
];ちなみに、ルート構成は、サブドメインの指定されたファイルのインポートをサポートしています。
<?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 ' ],
]
]; Alight Route:: get ( $ pattern , $ handler );
// Example
Alight Route:: get ( ' / ' , ' Controller::index ' );
Alight Route:: get ( ' / ' , [ ' Controller ' , ' index ' ]);
// Or try this to easy trigger hints from IDE
Alight Route:: get ( ' / ' , [Controller::class, ' index ' ]);
// With default args
Alight Route:: get ( ' post/list[/{page}] ' , [Controller::class, ' list ' ], [ ' page ' => 1 ]);
// Common HTTP request methods
Alight Route:: options ( ' / ' , ' handler ' );
Alight Route:: head ( ' / ' , ' handler ' );
Alight Route:: post ( ' / ' , ' handler ' );
Alight Route:: delete ( ' / ' , ' handler ' );
Alight Route:: put ( ' / ' , ' handler ' );
Alight Route:: patch ( ' / ' , ' handler ' );
// Map for Custom methods
Alight Route:: map ([ ' GET ' , ' POST ' ], ' test ' , ' handler ' );
// Any for all common methods
Alight Route:: any ( ' test ' , ' handler ' ); // Matches /user/42, but not /user/xyz
Alight Route:: get ( ' user/{id:d+} ' , ' handler ' );
// Matches /user/foobar, but not /user/foo/bar
Alight Route:: get ( ' user/{name} ' , ' handler ' );
// Matches /user/foo/bar as well, using wildcards
Alight Route:: get ( ' user/{name:.+} ' , ' handler ' );
// The /{name} suffix is optional
Alight Route:: get ( ' user[/{name}] ' , ' handler ' );
// Root wildcards for single page app
Alight Route:: get ( ' /{path:.*} ' , ' handler ' );Nikic/Fast-routeは、ルーティングパスのすべての正規表現を処理します。詳細については、Fastrouteの使用法を参照してください。
Alight Route:: group ( ' admin ' );
// Matches /admin/role/list
Alight Route:: get ( ' role/list ' , ' handler ' );
// Matches /admin/role/info
Alight Route:: get ( ' role/info ' , ' handler ' );
// Override the group
Alight Route:: group ( ' api ' );
// Matches /api/news/list
Alight Route:: get ( ' news/list ' , ' handler ' );AlightRoute::any()に含まれるメソッドをカスタマイズできます。
Alight Route:: setAnyMethods ([ ' GET ' , ' POST ' ]);
Alight Route:: any ( ' only/get/and/post ' , ' handler ' );ルートのハンドラーの前に共通コードを実行したい場合。
// For example log every hit request
Alight Route:: beforeHandler ([ svc Request::class, ' log ' ]);
Alight Route:: get ( ' test ' , ' handler ' );
Alight Route:: post ( ' test ' , ' handler ' );お勧めしませんが、コードに必要な場合:
// Effective in the current route file
Alight Route:: disableCache ();すべてのルーティングオプションは現在のファイルでのみ有効になり、次のファイルがインポートされる前にAlightRoute::init()によって自動リセットされます。例えば:
ファイル:config/admin.php
Alight Route:: group ( ' admin ' );
Alight Route:: setAnyMethods ([ ' GET ' , ' POST ' ]);
// Matches '/admin/login' by methods 'GET', 'POST'
Alight Route:: any ( ' login ' , ' handler ' );ファイル:config/web.php
// Matches '/login' by methods 'GET', 'POST', 'PUT', 'DELETE', etc
Alight Route:: any ( ' login ' , ' handler ' );変更されていないデータへのアクセス速度を最適化するために、ブラウザと共有キャッシュ(CDN)のキャッシュを制御するためのキャッシュコントロールヘッダーを送信します。
// Cache one day
Alight Route:: get ( ' about/us ' , ' handler ' )-> cache ( 86400 );
// Or force disable cache
Alight Route:: put ( ' user/info ' , ' handler ' )-> cache ( 0 );ユーザーログインステータスを管理するための簡単な認証ハンドラーを提供します。
// Define a global authorization verification handler
Alight Route:: authHandler ([ svc Auth::class, ' verify ' ]);
// Enable verification in routes
Alight Route:: get ( ' user/info ' , ' handler ' )-> auth ();
Alight Route:: get ( ' user/password ' , ' handler ' )-> auth ();
// No verification by default
Alight Route:: 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
Alight Route:: get ( ' user/rank/list ' , ' handler ' )-> auth ()-> cache ( 3600 );ファイル: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 ;
}
}多くの場合、ユーザーが送信したデータは処理に時間がかかりますが、処理する前に同じデータを受信したくありません。そのため、リクエストクールダウン時間を設定する必要があります。ユーザーは、クールダウン内で再度リクエストするときに429エラーを受け取ります。
// Cooldown only takes effect when authorized
Alight Route:: put ( ' user/info ' , ' handler ' )-> auth ()-> cd ( 2 );
Alight Route:: post ( ' user/status ' , ' handler ' )-> auth ()-> cd ( 2 );サードパーティのWebサイト(またはプロジェクトには複数のドメインがある)によるAJAXリクエストにAPIを使用する必要がある場合、CORSヘッダーのセットを送信する必要があります。具体的な理由から、Mozilla Docsを参照してください。
// Domains in config will receive the common cors header
Alight Route:: put ( ' share/config ' , ' handler ' )-> cors ();
// The specified domain will receive the common cors header
Alight Route:: put ( ' share/specified ' , ' handler ' )-> cors ( ' abc.com ' );
// The specified domain will receive the specified cors header
Alight Route:: put ( ' share/specified2 ' , ' handler ' )-> cors ( ' abc.com ' , ' Authorization ' , [ ' GET ' , ' POST ' ]);
// All domains will receive a 'Access-Control-Allow-Origin: *' header
Alight Route:: put ( ' share/all/http ' , ' handler ' )-> cors ( ' * ' );
// All domains will receive a 'Access-Control-Allow-Origin: [From Origin]' header
Alight Route:: put ( ' share/all/https ' , ' handler ' )-> cors ( ' origin ' );ウェブサイトがCDNを使用している場合は、このユーティリティを注意深く使用してください。ヘッダーがCDNによってキャッシュされた後の要求の失敗を避けるため。
lightは、「データベース」構成をcatfan/medooに直接渡します。特定の構成オプションについては、Medoo Getを参照してください。例えば:
ファイル: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() new MedooMedoo()の静的および単一のインスタンス実装であるため、 Medoo()のすべての機能を継承します。単一のインスタンスにより、各リクエストがデータベースに一度だけ接続して再利用し、データベース接続の数を効果的に削減します。
// Initializes the default database
$ db = Alight Database:: init ();
// Initializes others database with key
$ db2 = Alight Database:: 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 ();使用法の詳細については、Medooのドキュメントを参照してください。
Symfony/Cacheを使用して、複数のキャッシュドライバーと複数のキャッシュインターフェイスをサポートします。構成オプション「DSN」と「オプション」がキャッシュアダプターに渡されます。詳細は、利用可能なキャッシュアダプターを参照してください。例えば:
ファイル: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' => [],
// ],
// ]
];データベースと同様に、 AlightCache::init()同時リクエストのパフォーマンスを改善するために、キャッシュクライアントの静的および単一のインスタンス実装です。
// Initializes the default cache
$ cache = Alight Cache:: init ();
// Initializes others cache with key
$ cache2 = Alight Cache:: 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 = Alight Cache:: 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 ' );また、高度なキャッシングを使用するために、MemcachedまたはRedisネイティブインターフェイスをサポートします。
$ memcached = Alight Cache:: memcached ( ' memcached ' );
$ memcached -> increment ( ' increment ' );
$ redis = Alight Cache:: redis ( ' redis ' );
$ redis -> lPush ( ' list ' , ' first ' );Symfony/Cacheは10個以上のアダプターをサポートしていますが、ファイルシステム、Memcached、Redisなど、一般的に使用されている3つのみが組み込まれています。さらにアダプターが必要な場合は、拡張できます。例えば:
ファイル:config/app.php
<?php
return [
' app ' => [
' cacheAdapter ' => [ svc Cache::class, ' adapter ' ],
],
' cache ' => [
// ...
' apcu ' => [
' type ' => ' apcu '
],
' array ' => [
' type ' => ' array ' ,
' defaultLifetime ' => 3600
]
]
];ファイル:app/service/cache.php
namespace svc ;
use Symfony Component Cache Adapter ApcuAdapter ;
use Symfony Component Cache Adapter ArrayAdapter ;
use Symfony Component Cache Adapter NullAdapter ;
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 ;
}
}
}詳細については、Symfonyキャッシュコンポーネントを参照してください。
AlightApp::start()を介してすべてのエラーをキャッチします。アプリの構成で「デバッグ」をオンにすると、Pretty HTML( FILP/HOOPS )またはJSONでエラーが出力されます。
ファイル:config/app.php
<?php
return [
' app ' => [
' debug ' => true ,
]
];生産環境で「デバッグ」をオフにすると、HTTPステータスをファイルして出力するためにエラーを記録するだけです。これらのデフォルトの動作をアプリの構成によってオーバーライドできます。例えば:
ファイル:config/app.php
<?php
return [
' app ' => [
' errorHandler ' => [ svc Error::class, ' catch ' ],
' errorPageHandler ' => [ svc Error::class, ' page ' ],
]
];ファイル: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 ;
}
}
}定期的にPHPスクリプトをバックグラウンドで実行する必要がある場合。
$ sudo contab -eエンドラインに以下を追加します。
* * * * * sudo -u www-data /usr/bin/php /var/www/{PROJECT_DIRECTORY}/app/scheduler.php >> /dev/null 2>&1ファイル:config/job.php
Alight Job:: call ( ' handler ' )-> minutely ();
Alight Job:: call ( ' handler ' )-> hourly ();
Alight Job:: call ( ' handler ' )-> daily ();
Alight Job:: call ( ' handler ' )-> weekly ();
Alight Job:: call ( ' handler ' )-> monthly ();
Alight Job:: call ( ' handler ' )-> yearly ();
Alight Job:: call ( ' handler ' )-> everyMinutes ( 5 );
Alight Job:: call ( ' handler ' )-> everyHours ( 2 );
Alight Job:: call ( ' handler ' )-> date ( ' 2022-08-02 22:00 ' );各ハンドラーは一度に1つのプロセスのみを実行し、プロセスのデフォルトの最大ランタイムは1時間です。ハンドラーが長い実行時間が必要な場合は、Timelimit()を使用してください。
Alight Job:: call ( ' handler ' )-> hourly ()-> timeLimit ( 7200 ); // 7200 seconds aightは、プロジェクト内のファイルパスの形式を標準化するためにAlightApp::root()を下回っています。
// Suppose the absolute path of the project is /var/www/my_project/
Alight App:: root ( ' public/favicon.ico ' ); // /var/www/my_project/public/favicon.ico
// Of course, you can also use absolute path files with the first character '/'
Alight App:: root ( ' /var/data/config/web.php ' );構成内のファイルパスはすべてAlightApp::root()に基づいています。例えば:
Alight App:: 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
]);API応答の形式を標準化するためにAlightResponse::api()を照らします。
HTTP 200 OK
{
" error " : 0 , // API error code
" message ": " OK ", // API status description
" data": {} // Object data
}ステータス定義:
| HTTPステータス | APIエラー | 説明 |
|---|---|---|
| 200 | 0 | わかりました |
| 200 | 1xxx | 一般的なビジネスエラー、ユーザーにメッセージのみを表示します |
| 200 | 2xxx | 特別なビジネスエラー、ユーザーの次のアクションを定義する必要があります |
| 4xx | 4xx | クライアントエラー |
| 5xx | 5xx | サーバーエラー |
例えば:
Alight Response:: api ( 0 , null , [ ' name ' => ' alight ' ]);
// Response:
// HTTP 200 OK
//
// {
// "error": 0,
// "message": "OK",
// "data": {
// "name": "alight"
// }
// }
Alight Response:: api ( 1001 , ' Invalid request parameter. ' );
// Response:
// HTTP 200 OK
//
// {
// "error": 1001,
// "message": "Invalid request parameter.",
// "data": {}
// }
Alight Response:: api ( 500 , ' Unable to connect database. ' );
// Response:
// HTTP 500 Internal Server Error
//
// {
// "error": 500,
// "message": "Unable to connect database.",
// "data": {}
// }AlightはAlightResponse::render()を提供します。ビューテンプレートを表示し、テンプレートファイルのパスとオプションのテンプレートデータを使用してレンダリングメソッドを呼び出します。
ファイル:app/controller/pages.php
namespace ctr ;
class Pages
{
public static function index ()
{
Alight Response:: render ( ' hello.php ' , [ ' name ' => ' Ben ' ]);
}
}ファイル:app/view/hello.php
<h1>Hello, <?= $ name ?> !</h1>ファイル:config/route/web.php
Alight Route:: get ( ' / ' , [ ctr Pages::class, ' index ' ]);プロジェクトのホームページ出力は次のとおりです。
Hello, Ben!また、さまざまな名前空間に配置された有用なヘルパーもあります。詳細については、ファイルをクリックしてください。
| 名前空間 | ファイル |
|---|---|
| light request | request.php |
| light response | Response.php |
| light utility | utility.php |