ingeniasoftware / luthier-ci

Improved routing, middleware support, authentication tools and more for CodeIgniter 3 framework
https://luthier.ingenia.me/ci/en/
MIT License
150 stars 38 forks source link

Middleware #7

Closed mateusmcordeiro closed 6 years ago

mateusmcordeiro commented 6 years ago

Hi, could you pls give a way to do and use middlewares with your "Luthier-ci" like a "middleware example"?

andersonsalas commented 6 years ago

Hi,

A middleware is basically any PHP class stored in the application/middleware folder, with a a run() public method, the entry point. For example, this is a middleware named Test_middleware:

<?php
# application/middleware/Test_middleware.php

defined('BASEPATH') OR exit('No direct script access allowed');

class Test_middleware
{

    /**
     * Middleware entry point
     *
     * @return void
     */
    public function run()
    {
        echo "Hello!  ";
    }
}

It can be triggered in your routes with the following syntax:

<?php
#application/routes/web.php

// Group based middleware:
Route::group('/', ['middleware' => 'Test_middleware'], function(){

    Route::get('/', function(){
        echo 'Oi';
    });

    // Route based middleware:
    Route::get('/test', function(){
        echo 'Oi 2';
    }, ['middleware' => 'Test_middleware']);
});

The middleware can be an extension of the Controller, since we can retrieve the current framework instance using the ci() function. For example, it's possible to load a library inside a middleware:

<?php
# application/middleware/Test_middleware.php

defined('BASEPATH') OR exit('No direct script access allowed');

class Test_middleware
{

    /**
     * Middleware entry point
     *
     * @return void
     */
    public function run()
    {
        ci()->load->library('MyLibrary');
    }
}

A properly documentation will be added soon.