Mini-FWK는 성능에 중점을 둔 PHP 프레임 워크입니다. 다음과 같은 기능이 있습니다.
OBS :이 문서가 모든 프레임 워크 기능을 다루는 것은 아닙니다. 더 많은 예제 나 섹션을 추가하십시오.
다음 명령을 실행하여 예제 프로젝트를 복제하고 종속성을 설치하십시오.
$ git clone [email protected]:StartiOne/mini-fwk.git myproject
$ cd myproject
$ rm -Rf .git
$ cp .env.example .env 컨트롤러는 HTTP 요청에 대한 EntryPoint입니다. 특수 주석은 컨트롤러 방법에 대한 URL 및 중간 전쟁을 정의하는 데 사용됩니다. 예제 다음과 같은 폴더 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
}
} 중간 전위는 컨트롤러 방법 전에 일부 논리를 실행하는 데 유용합니다. 폴더 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 와 함께 작동하며 현재 지원되는 규칙은 필수, 문자열, 문자열, 텍스트, 정수, 플로트, 이중, 소수, 부울, 날짜, 데이터 타임, 시간, 이메일, maxlength, min, 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 스키마와 기본 데이터를 개발 및 생산 환경간에 동기화하기 위해서는 데이터 마이그레이션 및 시드가 필수적입니다. 마이그레이션을 만드는 방법에는 수동 및 자동입니다. 가장 일반적인 것은 엔티티 정의 및 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"또는 "-Test"플래그로 씨앗을 실행할 수 있습니다. 이 명령은 파일에없는 시드 테이블에서 모든 행을 제거합니다.
$ ./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/Centos1 단계 : .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 forever4 단계 : 일자리를 보냅니다
<?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 ' ]);소스 코드에서 더 많은 예를 확인할 수 있습니다