1. Go to this page and download the library: Download minimal/framework library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
App::dispatch(function () {
// Register additional services
App::register(['Demo' => DemoServiceProvider::class]);
// Respond on GET request
Router::get('/', function () {
return 'Hello from Minimal!';
});
// Respond on GET request with uri paramters
Router::get('hello/(:any)/(:num)', function ($any, $num) {
return 'Hello ' . $any . ' ' . $num ;
});
// Respond on POST request
Router::post('/', function () {
return Request::post();
});
// Respond with HTTP location
Router::get('redirection', function () {
Response::redirect('/');
});
// Respond with a view
Router::get('view', function () {
return View::render('fancy-html', ['param' => 'value']);
});
// Test the database connection
Router::get('database', function () {
DB::connections(Config::database());
return 'Successfully connected to database';
});
// Route group
Router::group([
'uriPrefix' => 'route-groups',
'namespace' => 'App\\Demo\\Base\\Controllers\\',
'middlewares' => [
'App\\Demo\\Base\\Middlewares\\CheckPermission',
'App\\Demo\\Base\\Middlewares\\ReportAccess',
]
], function () {
// Responds to GET route-groups/controller-action/with/middlewares'
Router::get('controller-action/with/middlewares', [
'middlewares' => ['App\\Demo\\Base\\Middlewares\\Cache' => [10]],
'controller' => 'YourController',
'action' => 'timeConsumingAction'
]);
// Do database stuff
Router::get('users', function () {
// Connect to database
DB::connections(Config::database());
// Truncate tables
Role::instance()->truncate();
User::instance()->truncate();
// Create 2 new roles
Role::create([['name' => 'admin'], ['name' => 'member']]);
// Get all the roles
$roles = Role::all();
// Create a user
$user = User::create(['username' => 'john']);
// Assign all roles to this user
$user->roles()->attach($roles);
// Get the first username 'john' with his roles
return $user->with('roles')->where(['username', 'john'])->first();
});
// ... subgroups are possible ...
});
});
Router::get('hello/(:any)/(:any)', function($firstname, $lastname) {
return 'Hello ' . ucfirst($firstname) . ' ' . ucfirst($lastname);
});
// (:segment) match anything between two slashes
// (:any) match anything until next wildcard or end of uri
// (:num) match integer only
// Router::get() responds to GET requests
// Router::post() responds to POST requests
// Router::put() ...you get it
// Router::patch()
// Router::delete()
// 1st parameter: string uri pattern
// 2nd parameter: a closure with return sends a response to the client, a array
// of key/value pairs sets the attributes of the route object, which are:
// 'controller': the controller class to load,
// 'action':, the method to execute
// 'uriPrefix': a string that prefixes the uri pattern
// 'middlewares': a multidimensional array of middleware with optional params
// 'params': array of values that will be injected to the method
class App\Demo\Base\Controllers\YourController
{
public function yourMethod($name, $lastname)
{
return 'Hello ' . ucfirst($name) . ' ' . ucfirst($lastname);
}
}
Router::group([
// Prefixes all urls in the group with 'auth/'
'uriPrefix' => 'auth',
// Define the class namespace for all routes in this group
// Will be prefixed to the controllers
'namespace' => 'App\\Demo\\Auth\\Controllers\\'
], function () {
// GET request: 'auth/login'
// Controller 'App\\Demo\\Auth\\Controllers\AuthController
Router::get('login', [
'controller' => 'AuthController',
'action' => 'loginForm' // Show the login form
]);
// POST request: 'auth/login'
// Controller 'App\\Demo\\Auth\\Controllers\AuthController
Router::post('login', [
'controller' => 'AuthController',
'action' => 'login' // Login the user
]);
/**
* Subgroup with middlewares
*/
Router::group([
// Middlewares apply to all route in this (sub)group
'middlewares' => [
// Check if the client is authorised to access these routes
'App\\Demo\\Auth\\Middlewares\\CheckPermission',
// Log or send a access report
'App\\Demo\\Auth\\Middlewares\\ReportAccess',
]
], function () {
// No access to these routes if middleware CheckPermission fails
// GET request: 'auth/users'
// Controller 'App\\Demo\\Auth\\Controllers\UserController
Router::get('users', [
'controller' => 'UserController',
'action' => 'list' // Show a list of users
]);
// etc...
});
});
class ClassA {}
class ClassB {}
class ClassC
{
public function __construct(InterfaceB $classB) {}
}
class MyClass
{
public function __construct(InterfaceA $classA, InterfaceC $classC) {}
}
class MyServiceProvider extends AbstractProvider
{
/**
* This is what happens when we call App::resolve('MyService')
*/
public function resolve()
{
// Do something before the class is instantiated
$time = time();
$settings = Config::item('settings');
// return new instance
return App::make(MyService::class, [$time, $settings]);
// ... or make singleton and resolve dependencies
return $this->singleton('MySingleton', App::make(App\\MyService::class, [
App::resolve('App\\MyOtherClassA'),
App::resolve('App\\MyOtherClassB'),
$time,
$settings
]);
}
/**
* Optional: Register additional config if needed
*/
public function config(): array
{
return [
'key' => 'value'
];
}
/**
* Optional: Register additional bindings if needed
*/
public function bindings(): array
{
return [
'SomeInterface' => SomeClass::class
];
}
/**
* Optional: Register additional services if needed
*/
public function providers(): array
{
return [
'SomeService' => SomeServiceProvider:class
];
}
/**
* Optional: Register additional event subscribers
*/
public function subscribers(): array
{
return [
'event.name' => EventSubscriber::Class
];
}
/**
* Optional: Register additional routes
*/
public function routes()
{
Router::get('my-service', MySerciceController::class . '@myControllerMethod')
}
}
$myService = App::resolve('MyService');
// in config/routes.php
Router::get('users', [
'controller' => 'UsersController',
'action' => 'list',
'middlewares' => [
// Check if the client is authorized to access this route
'App\\Middlewares\\checkPermission',
// Send a email to the administrator
'App\\Middlewares\\ReportAccess',
// Cache for x seconds
'App\\Middlewares\\Cache' => [(1*1*10)]
]
]);
// in app/Middlewares/CheckPermission.php
class CheckPermission implements MiddlewareInterface
{
...
// Inject what you want, instance is created through
// IOC::make() which injects any dependencies
public function __construct(
RequestInterface $request,
ResponseInterface $response,
RouteInterface $route
) {
$this->request = $request;
$this->response = $response;
$this->route = $route;
}
// Executed before dispatch
public function before() {
// If not authorised...
// ... send appropriate response ...
$this->response->addHeader();
$this->response->setContent();
$this->response->send()->exit();
// ... or redirect to login page
$this->response->redirect('login');
// ... or set error and cancel dispatch
$this->request->setError();
return false;
}
}
// in app/Middlewares/Cache.php
class Cache implements MiddlewareInterface
{
...
// Executed before dispatch
public function before() {
// return cached contents
}
// Executed after dispatch
public function after() {
// delete old cache
// create new cache
}
}
$result = Middleware::dispatch(function() {
return 'the task, for example FrontController::dispatch(Router::route())';
}, [
'App\\Middlewares\\checkPermission',
'App\\Middlewares\\ReportAccess',
'App\\Middlewares\\Cache' => [(1*1*10)]
]);
class MyController
{
public function __construct(MyModelA $myModelA, MyModelB $myModelB)
{
$this->modelA = $myModelA;
$this->modelB = $myModelB;
}
}
class MyControllerFactory extends AbstractProvider
{
public function resolve()
{
return new MyController('value1', 'value2');
}
}
class MyController
{
public function __construct($optionA, $optionB)
{
// $optionA is 'value1', $optionB is 'value2'
}
}
// The base directory to start from
View::setBase('../resources/views/');
// The theme directory in base directory, is optional and can be ingored
View::setTheme('my-theme');
// The layout file without '.php' from the base/theme directory
View::setLayout('layouts/my-layout');
// Set variables for the view
View::set('viewValue1', 'someValue1')
// By default variables are only accessible in the current view
// To share a variable $title across all layout and views
View::share('title', 'My title');
// Render a view without layout
View::view('pages/my-view', [
'viewValue2' => 'someValue2' // Same as View::set()
]);
// Render a view with layout, but in case of ajax only the view
View::render('pages/my-view', [
'viewValue2' => 'someValue2' // Same as View::set()
]);
class BaseController
{
public function __construct()
{
View::setBase(__DIR__'/../views/');
View::setTheme('my-theme');
View::setLayout('layouts/my-layout');
Assets::setBase(__DIR__'/../assets');
Assets::setTheme('my-theme');
}
}
class MyController extends BaseController
{
private $user;
public function __construct(UserInterface $user)
{
parent::__construct();
$this->user = $user;
}
public function myAction()
{
View::render('my-view', ['user' => $this->user->find(1)]);
}
}
// The base directory to start from
Assets::setBase('../app/Pages/resources/assets');
// The theme directory in base directory, is optional and can be ingored
Assets::setTheme('my-theme');
// Directory for css (default 'css')
Assets::setCssDir('css');
// Directory for js (default 'js')
Assets::setJsDir('js');
// Register css files
Assets::addCss(['normalize.css', 'main.css']);
//Register js files with keyword
Assets::addJs(['vendor/modernizr-2.8.3.min.js'], 'top');
// Register more js files with another keyword
Assets::addJs(['plugins.js', 'main.js'], 'bottom');
// Js from CDN
Assets::addExternalJs(['https://code.jquery.com/jquery-3.1.0.min.js'], 'bottom');
// Add inline javascript
Assets::addInlineScripts('jQueryFallback', function () use ($view) {
return View::render('scripts/jquery-fallback', [], true);
});