Mini-FWKは、パフォーマンスに焦点を当てるためのPHPフレームワークです。次の機能があります。
OBS:このドキュメントでは、すべてのフレームワーク機能をカバーしているわけではありません。より多くの例やセクションを追加してください。
次のコマンドを実行して、プロジェクトのサンプルをクローンし、依存関係をインストールします
$ git clone [email protected]:StartiOne/mini-fwk.git myproject
$ cd myproject
$ rm -Rf .git
$ cp .env.example .envコントローラーは、HTTPリクエストのエントリポイントです。特別な注釈は、コントローラーメソッドのURLとMiddlewaresを定義するために使用されます。フォルダーsrc/Controllersにコントローラーを保存します。
<?php
namespace App Controllers ;
use Mini Helpers Request ;
class ExampleController
{
/**
* @Get("/example")
* @Middleware("permission:SOME_PERMISSION")
*/
public function index ()
{
$ data = Request:: instance ()-> get ( ' data ' );
response ()-> json ([ ' data ' => $ data ]);
}
}デフォルトでは、URLルーティングに関連するファイルはsrc/routesに保存されます。コントローラーは注釈でルートを定義できるため、それらを編集する必要はありません。コントローラーの注釈からルートを生成するには、プロジェクトディレクトリ内で次のコマンドを実行します。
$ ./console route:scanMiniHelpersRequestおよびMiniHelpersResponseを使用してJSONを読み書きできます。次の例を参照してください。
<?php
namespace App Controllers ;
class RequestExampleController
{
/**
* @Get("/request-example")
*/
public function index ()
{
$ req = Mini Helpers Request:: instance ();
echo $ req -> get ( ' data.name ' ); // Get the key from the JSON input, $_REQUEST or $_FILES using *dots* to represent nested arrays
( new Mini Helpers Response )-> json ([ ' data ' =>[ ' token ' => ' ab ' ]], 200 ); // Output {data: {token: 'ab'}}
response ()-> json ([ ' data ' =>[ ' token ' => ' ab ' ]], 200 ); // Use a helper to do the same
}
}MiddleWaresは、コントローラーメソッドの前にロジックを実行するのに役立ちます。フォルダーsrc/Middlewaresにミドルウェアを保存してから、 src/routers/middlewares.phpを更新してください。
<?php
// src/routers/middlewares.php
return [
' permission ' => App Middlewares PermissionMiddleware::class
]; <?php
// src/Middlewares/PermissionMiddleware.php
namespace App Middlewares ;
class PermissionMiddleware
{
public function handler ( $ permission )
{
$ auth = app ()-> get ( ' App/Auth ' ); // Use the dependency container to store Auth class
$ token = $ auth -> getAccessToken ();
if ( $ token === null ) {
response ()-> json ([
' error ' => [
' code ' => ' 0001 ' ,
' detail ' => ' Unauthorized. ' ,
]
], 401 );
} else if ( $ auth -> hasPermission ( $ permission ) === false ) {
response ()-> json ([
' error ' => [
' code ' => ' 0001 ' ,
' detail ' => ' Forbidden. ' ,
]
], 403 );
}
}
}データ検証は、クラスMiniValidationValidatorで機能し、現在サポートされているルールは、必須、char、文字列、テキスト、整数、フロート、二重、小数、ブールン、日付、日付、時間、電子メール、maxlength、minlength、min、maxです。
ユニットテストの例を確認できます
<?php
namespace App Controllers ;
use Mini Helpers Request ;
use Mini Controllers BaseControllers ; // Implements validate and validateEntity
use App Models User ;
use App Models Retailer ;
class ValidationExampleController
{
/**
* @Get("/validation-example")
*/
public function index ()
{
// Complete example
$ validator = app ()-> get ( ' MiniValidationValidator ' );
$ validator -> setData (Request:: instance ()-> get ( ' data ' ))
$ validator -> validate ([
' name ' => ' string|required ' , // Rules are separeted by '|'
' addresses.*.street ' => ' string|required ' // Validate nested arrays inside 'addresses' key
]);
// Will throw ValidationException if error is found
echo ' Data successfuly validated ' ;
// Example using validate method. So you don't need a $validator instance
$ this -> validate ([
' name ' => ' string:6:255 ' , // Limit by length between 6 and 255 chars
]);
// Example using rules from model classe
$ this -> validateEntity ( new User );
// Example using multiple models
$ this -> validateEntities ([
' * ' => new Retailer ,
' owner ' => new User
]);
}
}サービスはsrc/Servicesに保存され、ビジネスロジックから個別のHTTPロジック(コントローラー)を含むために使用され、 MiniEntityDataMapper拡張できます。
モデルは「ユーザー」や「小売業者」などのビジネスオブジェクトを表し、属性スキーマに関連するデータを含んでいます。例に従って、 src/Modelsに保存されます。
<?php
namespace App Models ;
use Mini Entity Entity ;
use Mini Entity Behaviors QueryAware ;
class User extends Entity
{
use QueryAware; // Implement methods from MySQL ORM. Example: User::q()->listObject();
/**
* Table name used in MySQL
*
* @var string
*/
public $ table = ' users ' ;
/**
* Define fields 'updated_at' and 'created_at' to control timestamps
*
* @var bool
*/
public $ useTimeStamps = true ;
/**
* Define field 'deleted_at' to mark a row as deleted. Further calls to User::q() will automatically check for this field
*
* @type bool
*/
public $ useSoftDeletes = true ;
/**
* Field definition
*
* @type array
*/
public $ definition = [
' id ' => ' pk ' ,
' name ' => ' string ' ,
' password ' => ' string '
];
/**
* Fields that are filled and validated
*
* @var array
*/
public $ fillable = [
' name ' ,
' password '
];
/**
* Fields that are serialized with json_encode
*
* @var array
*/
public $ visible = [
' id ' ,
' name '
];
} MiniEntityQueryクラスで複雑なMySQLクエリを作成できます。例に従ってください。
<?php
use Mini Entity Query ;
use App Models User ;
// Complete example
$ query = ( new Query )
-> connection ( ' default ' )
-> from ( ' users ' )
-> alias ( ' u ' )
-> select ([ ' u.id ' , ' u.name ' , ' um.email ' ])
-> innerJoin ( ' user_emails um ' , ' um.user_id ' , ' = ' , ' u.id ' )
-> where ( ' id ' , ' = ' , 1 );
$ user = $ query -> getArray ();
// Generating an sql
$ sql = $ query -> makeSql ();
// Using entity query alias in a Model that uses the trait `MiniEntityBehaviorsQueryAware`
$ users = User:: q ()-> limit ( 0 , 1 )-> listObject (); // Can be listArray if you dont need an objectユニットテストの例を確認できます
MiniEntityMongoQueryクラスで複雑なMongoDBクエリを構築できます。例に従ってください。
<?php
use Mini Entity Mongo Query ;
use App Models User ;
// Complete example
$ chatMessages = ( new Query ( ' mongo ' , ' chat_messages ' ))
-> filter ( ' chat_id ' , 1 )
-> projection ([ ' description ' => 1 ])
-> sort ([ ' timestamp ' => 1 ])
-> skip ( 5 )
-> limit ( 10 )
-> listArray ();
// Using entity query alias in a Model that uses the trait `MiniEntityMongoBehaviorsMongoQueryAware`
$ chatMessages = ChatMessage:: q ()-> filter ( ' chat_id ' , 1 )-> listArray ();データの移行と種子は、開発と生産環境の間でMySQLスキーマとデフォルトデータを同期させるために不可欠です。移行を作成するには、手動と自動の2つの方法があります。最も一般的なのは、エンティティ定義とMySQL情報スキーマの違いを自動的にチェックする移行を生成することです。次の例を使用してください。
./console make:migration --diff # Create a migration for all tables
./console make:migration --diff --force # Force "alter tables" on "not null" columns
./console make:migration --diff --filter ' (permissoes|perfil_permissoes) ' # Check only tables matching the pattern
./console migrate # Run this after checking if the generated migration is ok他の瞬間には、手動で移行を作成する必要があります。次のコマンドを実行し、作成された移行を確認します。
$ ./console make:migration
Migration file created at ~ /PROJECT_FOLDER/migrations/Migration20170531174950.php <?php
use Mini Entity Migration AbstractMigration ;
class Migration20170531174950 extends AbstractMigration
{
public $ connection = ' default ' ;
public function up ()
{
// this method is auto-generated, please modify it to your needs
$ this -> addSql ( ' UPDATE users SET email = NULL WHERE email = ''' );
}
public function down ()
{
// this method is auto-generated, please modify it to your needs
}
}種子を使用する場合は、初期種子を使用するように注意してください。生産中に変更されたり、追加されたりしないものに対してのみ使用してください。
「Seeds/initial/your_table_name」または「Seeds/test/your_table_name」でファイルを作成します。
<?php
return [
' connection ' => ' default ' ,
' rows ' => [
[
' id ' => ' 1 ' , // Primary keys is required
' name ' => ' AdmFirewall ' ,
],
[
' id ' => ' 2 ' ,
' name ' => ' AdmVoice ' ,
]
]
];次に、「 - initial」または「 - テスト」フラグのいずれかでシードを実行できます。このコマンドは、ファイルにないシードテーブルからすべての行を削除します。
$ ./console db:seed --initialプロジェクトのルートディレクトリで利用可能なコンソール実行可能ファイルは、いくつかのフレームワーク固有のコマンドを実行できます。ただし、ユーザー生成コマンドを実行することもできます。
$ ./console make:command --name script:license:refresh --description " Update license file "
Command file created at ~ /PROJECT_FOLDER/src/Commands/ScriptLicenseRefresh.php <?php
namespace App Commands ;
use Mini Console Command AbstractCommand ;
use Commando Command as Commando ;
class ScriptLicenseRefresh extends AbstractCommand
{
/**
* @return string
*/
public function getName ()
{
return ' script:license:refresh ' ;
}
/**
* @return string
*/
public function getDescription ()
{
return ' Update license file ' ;
}
/**
* @param Commando $commando
*/
public function setUp ( Commando $ commando )
{
/**
* Example:
*
* $commando->option('name')
* ->describedAs('Command name, example: "script:invoice:process"')
* ->defaultsTo('');
*/
}
/**
* @param Commando $commando
*/
public function run ( Commando $ commando )
{
/**
* Example:
*
* echo $commando['name'];
*/
}
}その後、コマンドを実行できます
. /console script:license:refresh電子メールの送信やデータのインポートなどのいくつかのタスクは、バックグラウンドで実行する必要があります。労働者は、キューに囲まれたコマンドを待っているプロセスです。まず、マシンにBeanStalkdをインストールします。
$ apt-get install beanstalkd # Ubuntu/Debian
$ yum install beanstalkd # Fedora/Centosステップ1:.envファイルにBeanStalkdをセットアップします
printf ' WORKER_DRIVER=BEANSTALKDnBEANSTALKD_HOST="127.0.0.1"nBEANSTALKD_PORT=11300 ' >> .envステップ2: src/Workersでワーカークラスファイルを作成します
$ ./console make:worker --name ImportFileステップ3:ファイルsrc/Workers/ImportFileWorkerを編集し、ワーカーを実行します
$ ./console worker --run ImportFile # In production use something like supervisord to keep the process running foreverステップ4:ジョブを送信します
<?php
namespace App Controllers ;
use Mini Helpers Request ;
use Mini Workers WorkerQueue ;
class ExampleController
{
/**
* @Get("/example")
* @Middleware("permission:SOME_PERMISSION")
*/
public function index ()
{
WorkerQueue:: addQueue (
' SendEmail ' ,
[
' someparam ' => ' someargument '
]
);
}
}ファイルsrc/Application.phpを使用して、クラスをセットアップして例外を処理できます。例:
<?php
namespace Mini ;
use Throwable ;
/**
* Application
*
* Handle application specific behaviors using predefined hooks methods. You can extend it in your app
*
* @package Mini
*/
class Application
{
public function afterContainerSetUp ()
{
// Is exected before router initialize
}
public function afterConfigurationSetup ()
{
// Is exected before router initialize
}
public function onException ( $ exception )
{
if ( $ exception instanceof Mini Validation ValidationException) {
response ()-> json ([
' error ' => [
' detail ' => $ exception -> errors
]
], 400 );
} else {
response ()-> json ([
' error ' => [
' detail ' => $ exception -> getMessage () . ' ' . $ exception -> getTraceAsString ()
]
], 500 );
}
}
}フレームワークに伴ういくつかのグローバルな機能があります。例:
// Get an item from an array using "dot" notation.
array_get ( $ _POST , ' user.email ' );
// Get variables from .env file
env ( ' DATABASE_NAME ' );
// Filter array keys
array_only ([ ' name ' => ' John ' , ' password ' => ' 123 ' ], [ ' name ' ]);
// Exclude array keys
array_except ([ ' name ' => ' John ' , ' password ' => ' 123 ' ], [ ' password ' ]);ソースコードのより多くの例を確認できます