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:scan คุณสามารถอ่านและเขียน JSON ด้วย MiniHelpersRequest และ MiniHelpersResponse ดูตัวอย่างต่อไปนี้:
<?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 และกฎที่ได้รับการสนับสนุนในปัจจุบันคือ: จำเป็น, ถ่าน, สตริง, ข้อความ, จำนวนเต็ม, ลอย, double, ทศนิยม, บูลีน, วันที่, วันที่, เวลา, อีเมล, ความยาวสูงสุด, 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 Logic (คอนโทรลเลอร์) แยกต่างหากจากตรรกะทางธุรกิจและสามารถขยาย 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 '
];
} คุณสามารถสร้างแบบสอบถาม MySQL ที่ซับซ้อนด้วยคลาส MiniEntityQuery ทำตามตัวอย่าง
<?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คุณสามารถตรวจสอบตัวอย่างในการทดสอบหน่วย
คุณสามารถสร้างแบบสอบถาม MongoDB ที่ซับซ้อนด้วยคลาส MiniEntityMongoQuery ทำตามตัวอย่าง
<?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 schemas และข้อมูลเริ่มต้นในการซิงค์ระหว่างการพัฒนาและสภาพแวดล้อมการผลิต มีสองวิธีในการสร้างการย้ายถิ่น: ด้วยตนเองและอัตโนมัติ สิ่งที่พบบ่อยที่สุดคือการสร้างการย้ายถิ่นที่ตรวจสอบความแตกต่างในนิยามเอนทิตีของคุณโดยอัตโนมัติและสคีมาข้อมูล 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/intial/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: ตั้งค่า beanstalkd ในไฟล์. env ของคุณ
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 ' ]);คุณสามารถตรวจสอบตัวอย่างเพิ่มเติมเกี่ยวกับซอร์สโค้ด