Mini-FWK adalah kerangka kerja PHP untuk fokus pada kinerja. Ini memiliki fitur berikut:
OBS: Dokumentasi ini tidak mencakup semua fitur kerangka kerja. Jangan ragu untuk menambahkan lebih banyak contoh atau bagian.
Jalankan perintah berikut untuk mengkloning contoh proyek dan menginstal dependensi
$ git clone [email protected]:StartiOne/mini-fwk.git myproject
$ cd myproject
$ rm -Rf .git
$ cp .env.example .env Pengontrol adalah titik masuk untuk permintaan HTTP. Anotasi khusus digunakan untuk mendefinisikan URL dan Middlewares untuk metode pengontrol. Pengontrol toko di folder src/Controllers mengikuti contoh:
<?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 ]);
}
} Secara default, file yang terkait dengan routing URL disimpan dalam src/routes . Karena pengontrol dapat menentukan rute dengan anotasi, Anda tidak perlu mengeditnya. Untuk menghasilkan rute dari anotasi pengontrol Anda, jalankan perintah berikut di dalam direktori proyek Anda:
$ ./console route:scan Anda dapat membaca dan menulis JSON dengan MiniHelpersRequest dan MiniHelpersResponse . Lihat contoh -contoh berikut:
<?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 berguna untuk mengeksekusi beberapa logika sebelum metode pengontrol. Simpan Middlewares di folder src/Middlewares dan kemudian perbarui src/routers/middlewares.php Mengikuti contoh:
<?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 );
}
}
} Validasi data berfungsi dengan MiniValidationValidator dan aturan yang saat ini didukung adalah: wajib, char, string, teks, integer, float, double, desimal, boolean, tanggal, datetime, waktu, email, maxlength, minlength, min, max.
Anda dapat memeriksa contoh pada tes unit
<?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
]);
}
} Layanan disimpan dalam src/Services , mereka digunakan untuk berisi logika HTTP (pengontrol) terpisah dari logika bisnis dan dapat memperluas MiniEntityDataMapper .
Model mewakili objek bisnis seperti 'pengguna' atau 'pengecer' dan berisi data yang terkait dengan skema atribut. Mereka disimpan dalam src/Models mengikuti contoh:
<?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 '
];
} Anda dapat membangun kueri MySQL yang kompleks dengan kelas MiniEntityQuery . Ikuti contohnya.
<?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 objectAnda dapat memeriksa contoh pada tes unit
Anda dapat membangun kueri MongoDB yang kompleks dengan kelas MiniEntityMongoQuery . Ikuti contohnya.
<?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 ();Migrasi dan benih data sangat penting untuk menjaga skema MySQL dan data default secara sinkron antara lingkungan pembangunan dan produksi. Ada dua cara untuk menciptakan migrasi: secara manual dan otomatis. Yang paling umum adalah menghasilkan migrasi yang secara otomatis memeriksa perbedaan dalam definisi entitas Anda dan skema informasi MYSQL. Gunakan contoh berikut:
./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 okDi saat -saat lain, menciptakan migrasi secara manual akan diperlukan. Jalankan perintah berikut dan periksa migrasi yang dibuat.
$ ./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
}
}Saat menggunakan biji, berhati -hatilah untuk menggunakan benih awal hanya untuk hal -hal yang tidak akan berubah atau ditambahkan dalam produksi.
Buat file di 'seeds/inisial/your_table_name' atau 'seed/test/your_table_name' Mengikuti contoh ini:
<?php
return [
' connection ' => ' default ' ,
' rows ' => [
[
' id ' => ' 1 ' , // Primary keys is required
' name ' => ' AdmFirewall ' ,
],
[
' id ' => ' 2 ' ,
' name ' => ' AdmVoice ' ,
]
]
];Kemudian Anda dapat menjalankan biji dengan bendera "-inisial" atau "--tes". Perintah ini akan menghapus semua baris dari tabel unggulan Anda yang tidak ada dalam file.
$ ./console db:seed --initialKonsol yang dapat dieksekusi yang tersedia di direktori root proyek Anda dapat menjalankan beberapa perintah spesifik kerangka kerja. Tetapi dapat menjalankan perintah yang dibuat pengguna juga.
$ ./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'];
*/
}
}Maka Anda dapat menjalankan perintah Anda
. /console script:license:refreshBeberapa tugas seperti mengirim email dan mengimpor data perlu dieksekusi di latar belakang. Pekerja adalah proses yang berjalan menunggu perintah antrian. Pertama, pasang beanstalkd di mesin Anda.
$ apt-get install beanstalkd # Ubuntu/Debian
$ yum install beanstalkd # Fedora/CentosLangkah 1: Setup Beanstalkd di file .env Anda
printf ' WORKER_DRIVER=BEANSTALKDnBEANSTALKD_HOST="127.0.0.1"nBEANSTALKD_PORT=11300 ' >> .env Langkah 2: Buat file kelas pekerja di src/Workers
$ ./console make:worker --name ImportFile Langkah 3: Edit file src/Workers/ImportFileWorker dan jalankan pekerja
$ ./console worker --run ImportFile # In production use something like supervisord to keep the process running foreverLangkah 4: Kirim Pekerjaan
<?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 '
]
);
}
} File src/Application.php dapat digunakan untuk mengatur kelas dan menangani pengecualian. Contoh:
<?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 );
}
}
}Ada beberapa fungsi global yang datang dengan kerangka kerja. Contoh:
// 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 ' ]);Anda dapat memeriksa lebih banyak contoh kode sumber