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
}
} الأوساط المتوسطة مفيدة لتنفيذ بعض المنطق قبل طريقة وحدة التحكم. قم بتخزين الأدوات المتوسطة في المجلد 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 ، سلسلة ، نص ، عدد صحيح ، عطف ، مزدوج ، عشري ، منطقي ، تاريخ ، وقت ، الوقت ، البريد الإلكتروني ، maxlength ، 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 منفصل (وحدات التحكم) من منطق العمل ويمكن أن تمدد 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 والبيانات الافتراضية متزامنة بين بيئة التطوير وبيئة الإنتاج. هناك طريقتان لإنشاء ترحيل: يدويًا وتلقائيًا. الأكثر شيوعًا هو إنشاء ترحيل يتحقق تلقائيًا من الاختلافات في تعريف الكيان الخاص بك ومخطط معلومات 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
}
}عند استخدام البذور ، احرص على استخدام البذور الأولية فقط للأشياء التي لن تتغير أو تتم إضافتها في الإنتاج.
قم بإنشاء ملفات في "البذور/inial/your_table_name" أو "البذور/الاختبار/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 ' ]);يمكنك التحقق من المزيد من الأمثلة على رمز المصدر