01、Config中的Services.php代码如下:
<?phpnamespace Config;use App\Libraries\Tx_Auth; use CodeIgniter\Config\BaseService;class Services extends BaseService {//用户权限类public static function user_auth($getShared = true){echo '测试service能不能正常调用。';if ($getShared) {return static::getSharedInstance('user_auth');}return new Tx_Auth();} }
02、Libraries中的Tx_Auth.php代码如下:
<?phpnamespace App\Libraries;class Tx_Auth {//测试函数function test001(){ShowMessage('哈哈1!');}}
03、MyFilter代码如下:
<?phpnamespace App\Filters;use CodeIgniter\Filters\FilterInterface; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface;//use App\Config\Services;class MyFilter implements FilterInterface {public function before(RequestInterface $request,$arguments = null){$m_auth = service('user_auth');$m_auth->test001();echo '我是Filter中的一句话。';//加上这一句,就不往下执行了//exit; }public function after(RequestInterface $request,ResponseInterface $response,$arguments = null){// Do something here } }
04、效果如下:
05、浏览器效果如下: