Skip to content

Documentation

Amirul Islam Anirban edited this page Nov 5, 2023 · 16 revisions

Service Providers and Container

app/Providers: You can Register any application services and bootstrap any application service and want to do something before handling the request.

Make providers

To create a new providers, use the composer providers command:

composer providers

The command line interface will ask you for a provider name, you enter a name. It will automatically add "ServiceProvider" to the name you provided. For example you want to create a provider named "example". Then your provider class will be ExampleServiceProvider.php

After creating the provider add it to the provider array in the 'config/app.php' file.

'providers' => [
    App\Providers\ExampleServiceProvider::class,
],
namespace App\Providers;

use Devamirul\PhpMicro\core\Foundation\Application\Container\BaseContainer;
use Devamirul\PhpMicro\core\Foundation\Application\Container\Interface\ContainerInterface;

class ExampleServiceProvider extends BaseContainer implements ContainerInterface {

    /**
     * Register any application services.
     */
    public function register(): void {
        //
    }

    /**
     * Bootstrap any application services
     * and if you want to do something before handling the request.
     */
    public function boot(): void {
        //
    }

}

Bind container:

public function register(): void {

    $this->app->bind('example', function () {
        return new example();
    });

}

Resolve container:

app()->make('example');

Get all bound container:

app()->getBindings();

Configuration:

Open config folder, Here you will find some predefined files which you can modify as you wish.

The predefined config files are :- app.php auth.php auth.php database.php mail.php middleware.php

config:

As you can change as per your wish in "app.php".

return [
    /**
     * Application Name.
     */
    'app_name'  => env('APP_NAME', 'PhpMicroFramework'),

    /**
     * Application Url.
     */
    'app_url'   => env('APP_URL', 'http://localhost:8000'),

    /**
     * Application Home path.
     */
    'home_url'  => '/',

    /**
     * Application Timezone.
     */
    'timezone' => 'Asia/Dhaka',

    /**
     * Autoloaded All Service Providers.
     */
    'providers' => [
        AppServiceProvider::class,
        ApplicationContainer::class
    ],
];

Request and Response:

Request:

framework's Devamirul\PhpMicro\core\Foundation\Application\Request class provides an object-oriented way to interact with the current HTTP request being handled by your application as well as retrieve the input that were submitted with the request.

Accessing The Request:

You have 2 ways to access the session.

  1. You can get requests through the facade.
use Devamirul\PhpMicro\core\Foundation\Application\Facade\Facades\Request;

Request::input();
  1. You can get requests through the request helper function.
request()->all();

You get the following methods from the Request class.

// Get all input data.
request()->input();

// Get input data specified by key, return default data if key not found.
request()->input('name', 'default');

// Get input data specified by key.
request()->only('name', 'email');

// Get path.
request()->path();

// Get all query.
request()->query();

// Get query data specified by key.
request()->query('name');

// Get current method.
request()->method();

// Get all input data.
request()->all();

// Get dynamic params.
request()->getParam();

Also you will find some other methods.

isGet() isPost() isPut() isPatch() isDelete()

Response:

All routes and controllers should return a response to be sent back to the user's browser. The most basic response is returning a string from a route or controller.

Accessing The Response:

You can get some response helper function, you can do method chaining.

redirect('/link');

redirect('/link')->withData();

back();

back()->withError();

Routes:

routes/web.php: It is a simple and fast and lightweight route, inspired by Laravel route. You can do almost everything in this route as in Laravel route.

Routes accept a URI and a closure or a array, providing a very simple and expressive method of defining routes and behavior without complicated routing configuration files.

Router::get('/', [WelcomeController::class, 'index'])->name('welcome');

or

Router::get('/welcome', function(){
    return view('welcome');
})->name('user');

You can give each route a unique name.

Let's discuss the second parameter. The second parameter accepts a closure or an array of key value pairs. The 'key' of the array will be a class and the value will be a method of the class, the method will be invoked by the class.

use App\Controllers\WelcomeController;

Router::get('/', [WelcomeController::class, 'index'])->name('home');

Use return instead of echo.

// Right way.
Router::get('/greeting', function () {
    return 'Hello World';
});

// wrong way.
Router::get('/greeting', function () {
    echo 'Hello World';
});

Named Routes:

Named routes allow the convenient generation of URLs or redirects for specific routes. You may specify a name for a route by chaining the name method onto the route definition:

Route names should always be unique.

Router::get('/user/profile', function () {
    // ...
})->name('profile');

Generating URLs To Named Routes

Once you assign a name to a given route, you can redirect via toRoute():

return toRoute('profile');

If the named route defines parameters, you may pass the parameters as the second argument to the toRoute function. The given parameters will automatically be inserted into the generated URL in their correct positions:

Router::get('/user/:id/profile', function () {
    // ...
})->name('profile');

return toRoute('profile', ['id' => 1]);

If you pass additional parameters in the array, those key / value pairs will automatically be added to the generated URL's query string:

Router::get('/user/:id/profile', function () {
    // ...
})->name('profile');

return toRoute('profile', ['id' => 1, 'photos' => 'yes']);

Route Parameters:

Required Parameters:

Sometimes you will need to capture segments of the URI within your route. For example, you may need to capture a user's ID from the URL. You can get it through $request->getParam() method.

Router::get('/user/:id', function (Request $request) {
    return 'User ' . $request->getParam('id');
});

You may define as many route parameters as required by your route:

Router::get('/posts/:post/comments/:comment', function (Request $request) {
    //Get all parameters array.
    return 'User ' . $request->getParam();

    //Get specific parameter.
    return 'User ' . $request->getParam('post');
});

Route parameters will always start with Colon ':' and should contain alphanumeric characters.

Parameters:

Automatically get 'Request' instances in your route callback or controller.

In callback:

Router::get('/user/:id', function (Request $request) {
    return 'User ' . $request->getParam('id');
});

In controller:

Router::get('/user/:id', [UserController::class, 'index']);
namespace App\Http\Controllers;

use Devamirul\PhpMicro\core\Foundation\Application\Request\Request;
use Devamirul\PhpMicro\core\Foundation\Controller\BaseController;

class UserController extends BaseController {
    public function index(Request $request) {
        return 'User ' . $request->getParam('id');
    }
}

Optional Parameters:

Occasionally you may need to specify a route parameter that may not always be present in the URI. You may do so by placing a question sign ? mark after the parameter:

It is important to note that optional parameter are always placed at the end of the URLs. Optional parameters cannot be checked with regular expressions.

Router::get('/user/:name?', function () {
    //
});

Regular Expression Constraints:

You can restrict the format of your route parameter by using the where method on a route instance. The where() method takes a regular expression as parameter which determines how the parameter should be delimited. The "where()" method will accept the serialized parameters of the router's dynamic parameters:

Router::get('/user/:id', function () {
    // ...
})->where(['id' => '^\d+$']);

Router::get('/user/:id', function () {
    // ...
})->where(['id' => '^\d+$']);

Sometimes you may need to register a route that responds to multiple HTTP verbs. You may do so using the match method. Or, you may even register a route that responds to all HTTP verbs using the any method:

Router::match(['get', 'post'], '/', function () {
    // ...
});

Router::any('/', function () {
    // ...
});

Redirect Routes:

If you are defining a route that redirects to another URI, you may use the redirect() method. This method provides a convenient shortcut so that you do not have to define a full route

Router::redirect('/here', '/there');

Middlewares:

Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application.

The predefined middleware files are :- AuthMiddleware.php GuestMiddleware.php CsrfMiddleware.php

By default you will get request instance in handle method.

Make middleware:

To create a new middleware, use the composer middleware command:

composer middleware

The command line interface will ask you for a middleware name, you enter a name. It will automatically add "Middleware" to the name you provided. For example you want to create a middleware named "example". Then your middleware class will be ExampleMiddleware.php

namespace App\Http\Middlewares;

use Devamirul\PhpMicro\core\Foundation\Application\Request\Request;
use Devamirul\PhpMicro\core\Foundation\Middleware\Interface\Middleware;

class AuthMiddleware implements Middleware {
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, array $guards) {
        //
    }
}

For example, This framework includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to your application's login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

use Devamirul\PhpMicro\core\Foundation\Application\Facade\Facades\Auth;
use Devamirul\PhpMicro\core\Foundation\Application\Request\Request;

public function handle(Request $request, array $guards) {
    if (!empty($guards)) {
        foreach ($guards as $guard) {
           if ($guard === 'editor' && Auth::guard($guard)->check()) {
               return;
           }
           return redirect('/editors/login');
        }
    } elseif (!Auth::check()) {
        return redirect('/login');
    }
    return;
}

Add middleware

After creating the middleware add it to the middleware array in the 'config/middleware.php' file. Add your own middleware to this list and assign it an alias of your choice:

'middleware' => [
    'auth'  => App\Http\Middlewares\AuthMiddleware::class,
    'guest' => App\Http\Middlewares\GuestMiddleware::class,
    'csrf'  => Devamirul\PhpMicro\core\Foundation\Middleware\Middlewares\CsrfMiddleware::class,
],

If you would like to assign middleware to specific routes, you may invoke the middleware method when defining the route. Once the middleware alias is defined, you use the alias when assigning middleware to routes:

Router::get('/users/:id', function(int $id){
    return 'User id - ' . $id;
})->middleware('auth');

You can assign multiple middleware at once if you want:

Router::get('/users/:id', function(int $id){
    return 'User id - ' . $id;
})->middleware(['auth','csrf']);

Middleware Parameters:

We can optionally pass the guard name as a parameter to the middleware if there is multiple auth using guard.

Router::get('/login', [AuthenticatedController::class, 'create'])->name('login')->middleware('guest:editor');

Handle middleware arguments:

public function handle(Request $request, array $guards) {
    if (!empty($guards)) {
        foreach ($guards as $guard) {
           if ($guard === 'editor' && Auth::guard($guard)->check()) {
               return;
           }
           return redirect('/editors/login');
        }
    } elseif (!Auth::check()) {
        return redirect('/login');
    }
    return;
}

CSRF Protection:

Remember, any HTML forms pointing to POST, PUT, PATCH, or DELETE routes that are defined in the web routes file should include a CSRF token field. Otherwise, the request will be rejected.

<form method="POST" action="/profile">
    <?=setCsrf()?>
    ...
</form>

Set default middlewares:

If you want to set some middleware to Https verbs by default, you can do that very easily, The defined middleware will run when that https method request is handled:

Open config/middleware.php

'get'        => [],
'post'       => [ 'csrf' ],
'put'        => [ 'csrf' ],
'patch'      => [ 'csrf' ],
'delete'     => [ 'csrf', 'auth' ],

Controllers:

app/Http/Controllers: Controllers respond to user actions (submitting forms, show users, any action etc.). Controllers are classes that extend the BaseController class.

Controllers are stored in the app/Controllers folder. A sample Welcome controllers are included. Controller classes need to be in the App/Controllers namespace. You can add subdirectories to organize your controllers.

By default you will get request instance in each method.

Make controller

To create a new controller, use the composer controller command:

composer controller

The command line interface will ask you for a controller name, you enter a name. It will automatically add "Controller" to the name you provided. For example you want to create a controller named "example". Then your controller class will be ExampleController.php

namespace App\Http\Controllers;

use Devamirul\PhpMicro\core\Foundation\Application\Request\Request;
use Devamirul\PhpMicro\core\Foundation\Controller\BaseController;

class UserController extends BaseController {
    /**
     * User show method.
     */
    public function show(Request $request) {
        return 'user name -' . $request->input('name');
    }
}

Views:

Views are used to display information. Views separate your controller / application logic from your presentation logic and are stored in the resources/views directory. No database access or anything like that should occur in a view file.

Fortunately you get a helper function of the main 'view' class.

Router::get('/welcome', function(){
    return view('welcome');
})->name('welcome');

If you want to pass data to "view" files, you may pass an array of data to views to make that data available to the view:

return view('welcome', ['name' => 'Amirul']);

When passing information in this manner, the data should be an array with key / value pairs. After providing data to a view, you can then access each value within your view using the data's keys, such as

<?php echo $name; ?>

You can send a status code if you want.

return status(200)->view('welcome');

You can set a different layout for the "view" file if you want. By default the layout will be "app.view.php".

return layout('main')->view('welcome');

or

return layout('main')->status(200)->view('welcome');

Models:

Models are used to get and store data in your application. They know nothing about how this data will be presented in the views. Models extend the src\core\Foundation\Model class and use PDO to access the database (by Medoo). They're stored in the app/Models folder.

namespace App\Models;

use Devamirul\PhpMicro\core\Foundation\Models\BaseModel;

class Users extends BaseModel {
    protected $table = 'editors'
}

If your model's corresponding database table does not fit this convention, you may manually specify the model's table name by defining a table property on the model:

protected $table = 'editors'

Database:

Migrations

You can easily create database tables through migration.

Create migration:

You may use the 'composer create' command to generate a database migration. The new migration will be placed in your 'database/migrations' directory.

composer create

The command line interface will ask you for a table name, you enter a name. It will automatically add "_table" to the name you provided. For example you want to create a table named "users". Then your migration class will be users_table.php.

Also it will ask you if you want a model and controller relative to the table name. You can press 'y' if you want it or 'n' if you don't want it.

When you press 'y' it will automatically create a model and controller matching the table name you provided. For example you want to create a table called "users". Then your model class will be users.php and controller class will be UsersController, it will automatically add Controller at the end.

The migration file will look like this:

use Devamirul\PhpMicro\core\Foundation\CLI\Database\Base\BaseMigration;

class users_table extends BaseMigration {

    /**
     * Run the migrations.
     */
    public function up() {
        return static::db()->create('users', [
            'id'          => [
                'INT',
                'NOT NULL',
                'AUTO_INCREMENT',
                'PRIMARY KEY',
            ],
            'name'        => [
                'VARCHAR(30)',
                'NOT NULL',
            ],
            'created_at'  => [
                'TIMESTAMP',
                'NOT NULL',
                'DEFAULT CURRENT_TIMESTAMP',
            ],
            'updated_at'  => [
                'TIMESTAMP',
                'NOT NULL',
                'DEFAULT NOW()',
                'ON UPDATE NOW()',
            ],
        ]);
    }
}

Running migrations:

To run all of your outstanding migrations, execute the composer migrate command:

composer migrate

Drop migrations:

The composer drop command will drop all tables from the database:

composer drop

Connect database:

Almost every modern web application interacts with a database. micro framework makes interacting with databases extremely simple across a variety of supported databases using SQL.

Medoo is handling all queries with SQL-92 standard. You should keep in mind the quotation marks in the query, or use prepared statements to prevent SQL injection as possible.

Internally it uses a PHP database package called Medoo.

The configuration for database services is located in your application's config/database.php configuration file. In this file, you may define all of your database connections, as well as specify which connection should be used by default.

Config:

return [
    /**
     * Default Database Connection Name.
     */
    'default'     => env('DB_CONNECTION', 'mysql'),

    /**
     * Define multiple database Configurations.
     */
    'connections' => [
        'mysql' => [
            'driver'   => 'mysql',
            'host'     => env('DB_HOST', '127.0.0.1'),
            'port'     => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'php_micro_framework'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'error'    => env('DB_ERROR', 'PDO::ERRMODE_EXCEPTION'),
        ],
    ],
];

Get database instance:

DB::db() actually returns a Medoo singleton instance behind the scenes.

DB::db();

You can easily perform tasks using model.

Model:

If your model's corresponding database table does not fit this convention, you may manually specify the model's table name by defining a table property on the model:

protected $table = 'editors'

The target columns of data will be fetched and The WHERE clause to filter records. select($columns, $where(optional))

$user = new User();

$user->select([
    "user_name",
    "email"
], [
    // Where condition.
    "user_id[>]" => 100
])->getData();

Table Joining:

SQL JOIN clause can combine rows between two tables. Medoo provides a simple syntax for the JOIN clause.

[>] ==> LEFT JOIN [<] ==> RIGHT JOIN [<>] ==> FULL JOIN [><] ==> INNER JOIN

$user = new User();

$user->select([
    // Here is the table relativity argument that tells the relativity between the table you want to join.
    "[>]account" => ["author_id" => "user_id"]
], [
    "post.title",
    "account.city"
])->getData();

Data Mapping:

$user = new User();

$user->select([
    "[>]account" => ["user_id"]
], [
    "post.content",

    "userData" => [
        "account.user_id",
        "account.email",

        "meta" => [
            "account.location",
            "account.gender"
        ]
    ]
], [
    "LIMIT" => [0, 2]
])->getJson()->getData();

Insert:

Insert one or more records into the table. insert($values)

$user = new User();

$user->insert([
    [
        "user_name" => "foo",
        "email" => "foo@bar.com",
    ],
    [
        "user_name" => "bar",
        "email" => "bar@foo.com",
    ]
]);
// Get last inserted id.
$user->id();

Errors And Error Handling:

$user = new User();

$user->select([
    "user_name",
    "email"
])->getData();

// DB::db()->error and DB::db()->errorInfo will be null value if no error occurred.
// You can simply check if the value is null or not to know about that.
if ($user->error()) {
    echo "Error happened!";
};

See the Medoo documentation for details.

You can invoke all methods of Medoo from the model.

However, 2 things should be noted.

  1. You cannot use the table names shown in the "sql query " in the Medoo documentation, because the framework will magically choose the table names based on the model. So model name and table name should be same.

In meddo documention

// Here the table name "user" is used.
DB::db()->select("users", [
    "user_name",
    "email"
]);

In framework

// Here automatically the table name will be obtained from the "new User()" model.
$user = new User();

$user->select([
    "user_name",
    "email"
]);
  1. Also you need to use "getData()" method to get the data.

In meddo documention

$user = DB::db()->select("users", [
    "user_name",
    "email"
]);

print_r($user);

In framework

$user = new User();

$user = $user->select([
    "user_name",
    "email"
])->getData();

print_r($user);

Also run customized raw queries easily.

Raw Query:

query($query)

DB::db()->query("SELECT email FROM account")->fetchAll();

The query() also supports prepared statements. Medoo will auto-detect the data type for input parameters.

DB::db()->query(
    "SELECT * FROM <account> WHERE <user_name> = :user_name AND <age> = :age", [
        ":user_name" => "John Smite",
        ":age" => 20
    ]
)->fetchAll();

Medoo is based on the PDO object. You can access the PDO object directly via using $database->pdo, so that you can use all PDO methods if you needed, like prepare, transaction, rollBack, or more.

Transaction:

DB::db()->pdo->beginTransaction();

DB::db()->insert("account", [
    "user_name" => "foo",
    "email" => "foo@bar.com",
    "age" => 25
]);

/* Commit the changes */
DB::db()->pdo->commit();

/* Recognize mistakes and roll back changes */
DB::db()->pdo->rollBack();

Create a table:

create($table, $columns, $options)

DB::db()->create("account", [
    "id" => [
        "INT",
        "NOT NULL",
        "AUTO_INCREMENT",
        "PRIMARY KEY"
    ],
    "first_name" => [
        "VARCHAR(30)",
        "NOT NULL"
    ]
]);

Guards:

config/auth.php: The framework offers you a "guard" system for multiple authentication. You can use multiple guards there if you want.

return [
    /**
     * Set Default authentication guards.
     */
    'defaults' => 'web',

    /**
     * Define multiple guards.
     */
    'guards'   => [
        'web'    => [
            'provider' => 'users',
            'model' => App\Models\Users::class,
        ],

        'editor' => [
            'provider' => 'editors',
            'model' => App\Models\Editors::class,
        ],
    ],
];

Forms:

Use the form here like a normal 'html' form. In the action attribute of the form you enter a URL.

You must set CSRF token inside the form. Otherwise get a 'CsrfErrorException'.

Example:

<?=setCsrf()?>
<form action="/login" method="POST" class="mt-5">

    <?=setCsrf()?>

    <div class="mb-3">
        <label for="exampleInputEmail" class="form-label">Email address</label>
        <input type="email" name="email" class="form-control" id="exampleInputEmail" aria-describedby="emailHelp">
        <div id="emailHelp" class="form-text"> <?= errors('email')?> </div>
    </div>

    <div class="mb-3">
        <label for="exampleInputPassword" class="form-label">Password</label>
        <input type="password" name="password" class="form-control" id="exampleInputPassword">
        <div id="emailHelp" class="form-text"> <?= errors('password')?> </div>
    </div>

    <button type="submit" class="btn btn-primary">Login</button>

    <a class="mx-5" href="/forgot-password">Forgot password?</a>
    <div>
        <br>
        <a class="" href="/register">Create an account</a>
    </div>
</form>

Validation:

Micro Framework provides a nice and easy way to validate incoming data to your application. For validation, Micro Framework uses a package called Rakit Validation behind the scenes.

Features:

  • API like Laravel validation.
  • Array validation.
  • $_FILES validation with multiple file support.
  • Custom attribute aliases.
  • Custom validation messages.
  • Custom rule.

There are two ways to validating data with this library. Using make to make validation object, then validate it using validate. Or just use validate.

Examples:

require('vendor/autoload.php');

use Rakit\Validation\Validator;

$validator = new Validator;

$validation = $validator->validate(request()->input(), [
    'email'                 => 'required|email',
    'password'              => 'required|min:6',
    'confirm_password'      => 'required|same:password',
]);

if ($validation->fails()) {
    // handling errors
    $errors = $validation->errors();

    return back()->withError($errors);
} else {
    // validation passes
    echo "Success!";
}

Get & Show validation errors:

<?= errors('email')?>

With Example:

<form>
   <div class="mb-3">
       <label for="exampleInputEmail" class="form-label">Email address</label>
       <input type="email" name="email" class="form-control" id="exampleInputEmail" aria-describedby="emailHelp">

       <div id="emailHelp" class="form-text"> <?= errors('email')?> </div>
   </div>
</form>

See the Rakit package documentation for details.

But one thing should be noted.

  • The Rakit package uses the "$_post" method to capture form input data. But you should use 'request()->input()' or 'request()->all()' or 'request()->only('email')' method.

Example:

In Rakit package:

$validation = $validator->validate($_POST, [
    'email'                 => 'required|email'
]);

In framework:

$validation = $validator->validate(request()->input(), [
    'email'                 => 'required|email'
]);

Authentication:

Many web applications provide a way for their users to authenticate with the application and "login". Implementing this feature in web applications can be a complex and potentially risky endeavor. For this reason, Micro framework strives to give you the tools you need to implement authentication quickly, securely, and easily.

Authentication Documentation

Mail:

Almost every modern web application provides mailing system . The framework helps you send mails very easily. It is very simple, below we will see its example.

Framework's email services may be configured via your application's 'config/mail.php' configuration file.

return [
    /**
     * Mailer Configurations.
     */
    'smtp'    => [
        'host'         => env('MAIL_HOST', 'sandbox.smtp.mailtrap.io'),
        'port'         => env('MAIL_PORT', 587),
        'username'     => env('MAIL_USERNAME', ''),
        'password'     => env('MAIL_PASSWORD', ''),
    ],

    /**
     * Global "From" Address.
     */
    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
        'name' => env('MAIL_FROM_NAME', 'PhpMicroFramework'),
    ],
];

Get mailer instance:

use Devamirul\PhpMicro\core\Foundation\Application\Mail\Mail;

Mail::mailer();

Send mail example:

// Default address from config file.
$mailConfig = config('mail', 'from');

// Send mail.
Mail::mailer()
        ->setFrom($mailConfig['name'], $mailConfig['address'])
        ->addTo('User', 'user@mail.com')
        ->setSubject('Welcome')
        ->setBody('Dear <strong>User</strong>, Thank you for registering')
        ->send();

Event:

Almost every modern web application provides event listener system. Micro framework's events provide a simple observer pattern implementation, allowing you to listen for various events that occur within your application And you can trigger events when needed.

Accessing The Request:

You can get events through the event helper function.

event();

Example:

public function boot(): void {

    event()->listen('welcome', function(){
        return 'welcome message';
    });

}

Router::get('/welcome', function(){
    return event()->trigger('welcome');
});

Sessions:

Since HTTP driven applications are stateless, sessions provide a way to store information about the user across multiple requests that can be accessed from subsequent requests.

The session can basically be divided into 2 parts.

  1. Session

  2. FlushSession

Session:

Accessing The Session:

You can store any type of data here. You have 2 ways to access the session.

  1. You can get session through the facade.
use Devamirul\PhpMicro\core\Foundation\Application\Facade\Facades\Session;

Session::set('example', 'example session string');
  1. You can get session through the session helper function.
session()->get('example');

Example:

// Return bool.
session()->has('example');
Session::has('example');

// Destroy session data by key.
session()->delete('example');
Session::delete('example');

FlushSession:

Sometimes you may wish to store items in the session for the next request. You may do so using the flushMessage() method. Data stored in the session using this method will be available immediately and during the subsequent HTTP request. After the subsequent HTTP request, the flashed data will be deleted. Flash data is primarily useful for short-lived status messages:

Accessing The FlushSession:

You can store any type of data here. You have 2 ways to access the FlushSession.

  1. You can get FlushSession through the facade.
use Devamirul\PhpMicro\core\Foundation\Application\Facade\Facades\Flush;

Flush::set('example', 'example session string');
  1. You can get FlushSession through the FlushSession helper function.
flushMessage()->get('example');

Example:

// Return bool.
flushMessage()->has('example');
Flush::has('example');

// Destroy session data by key.
Flush::delete('example');

Helpers:

Micro frameworks provide some helper methods for the convenience of developers.

Helpers Documentation