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

Call to a member function run() on null #22

Closed iftieaq closed 5 years ago

iftieaq commented 5 years ago

I am getting this error

Fatal error: Call to a member function run() on null in ...\application\controllers\PageController.php on line 8

And this is my controller looks like

class PageController extends CI_Controller {
    public function __construct () {
        $this->middleware->run('PreMiddleware');
    }
}

And this is the middleware I made so far

class PreMiddleware implements Luthier\MiddlewareInterface
{
    public function run( $args )
    {
        ci()->load->view('layouts/header');
    }
}

As far as I know CI_Controller doesn't have any middleware property. So it's obvious that $this->middleware will be null. So the question is, how can I run a middleware inside a controller.

andersonsalas commented 5 years ago

Hi @ifty-rahman!

Due CodeIgniter limitations you can't run a middleware within the controller constructor (the $middleware property is injected by Luthier CI after the controller constructor)

You can, in change, run a middleware in any other method of your controller:

<?php

class PageController extends CI_Controller {
    public function __construct () {
        parent::__construct();
    }

   public function index()
   { 
          $this->middleware->run('PreMiddleware');
   }
}