Mini-FWK是PHP框架,專注於性能。它具有以下功能:
OBS:此文檔不涵蓋所有框架功能。隨時添加更多示例或部分。
運行以下命令以克隆示例項目並安裝依賴項
$ git clone [email protected]:StartiOne/mini-fwk.git myproject
$ cd myproject
$ rm -Rf .git
$ cp .env.example .env控制器是HTTP請求的入口點。特殊註釋用於定義控制器方法的URL和中間Wares。按照以下示例的文件夾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:scan您可以使用MiniHelpersRequest和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對於控制器方法之前執行一些邏輯很有用。將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,char,string,文本,整數,float,float,double,double,Decimal,boolean,日期,日期,日期,時間,時間,電子郵件,最大長度,最低長度,最小值,最小,最大。
您可以檢查單位測試的示例
<?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模式和默認數據在開發環境和生產環境之間的同步至關重要。創建遷移的方法有兩種:手動和自動。最常見的是生成一個遷移,該遷移會自動檢查實體定義和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
}
}使用種子時,請謹慎使用初始種子,僅用於不會改變或在生產中添加的事物。
在此示例之後,在“ seed/pinitials/your_table_name”或“ seed/test/your_table_name”中創建文件:
<?php
return [
' connection ' => ' default ' ,
' rows ' => [
[
' id ' => ' 1 ' , // Primary keys is required
' name ' => ' AdmFirewall ' ,
],
[
' id ' => ' 2 ' ,
' name ' => ' AdmVoice ' ,
]
]
];然後,您可以使用“ - 判斷”或“ - 測試”標誌運行種子。此命令將從文件中未從您的種子表中刪除所有行。
$ ./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 ' ]);您可以查看源代碼的更多示例