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 ' ]);您可以查看源代码的更多示例