容器的功能实例一次多次调用,绑定函数:bind()——快速调用类库, app()——助手函数,对已绑定的类,快速实例化
// 绑定类库标识 绑定类名与Closure到app->$bind 实例到app->$instances 调用时根据情况去实例化
$this->app->bind('Cache1', 'think\Cache');//$this->app同app() //服务类中bind数组
$this->app->cache1='think\Cache';//通过container()->__set实现
$this->app['cache1']='think\Cache';
app()->cache1='think\Cache';
app()['cache1']='think\Cache';
bind('cache2', 'think\Cache');//助手函数
//实例 参考上面
$cache1 = app('Cache1');
$cache1 = app()->Cache1;//通过container()->__get实现
//调用方法
$cache1->set('name','12313');
app('Cache1')->set('name','12313');
//输出
echo $cache1->get('name');
//结果
12313批量绑定(app/provider.php)只支持全局,不能单独定义。
return [ 'route' => \think\Route::class, 'session' => \think\Session::class, 'url' => \think\Url::class, ];
服务:指执行框架的某些组件或者功能的时候需要依赖的一些基础类库(如session,cache等)应用中定义的服务先系统服务register,可以直接在应用的register()中做验证码输出,缓冲输出,虽然违背服务初衷但节省性能
register方法,用于框架启动之前,将服务绑定到容器中(提前加载好需要的类库),也可在服务bind中给定,在/app下定义应用服务/app/AppService.php
<?php
declare (strict_types = 1);
namespace app;
use think\Service;
/**
* 应用服务类
*/
class AppService extends Service
{
//如果只是bind,也可以bind数组取代register
public function register()//可选
{
$this->app->bind('session1', \think\Session::class);
}
public function boot()
{
// 服务启动 可选
}
}框架通过/app/service载入应用服务
use app\AppService; // 系统服务定义文件 // 服务在完成全局初始化之后执行 return [ AppService::class,//php内部转换成串'app\AppService'; 等同于'app\AppService' ];
服务载入流程 先应用服务regiser(把AppService实例化到app->services[])->系统服务register()->按register顺序boot()
1、中间件是什么?
主要用于拦截或过滤应用的HTTP请求。 新版部分核心功能使用中间件处理,你可以灵活关闭。包括Session功能、请求缓存和多语言功能。
2、多应用模式下中间件分类:
全局中间件->应用中间件->路由中间件->控制器中间件
事件
事件先通过listen定义或bind,然后通过trigger调用,系统可以看成是5.1版本行为系统的升级版
1、通过监听事件,进行类的调用。(观察者模式)
//手动创建app\listenter文件目录,文件夹里面创建事件监听类
Event::listen('UserLogin', 'app\listener\UserLogin');//手动监听
或
'listen' => [ //事件定义文件中监听 /app/event.php
'AppInit' => [],
'HttpRun' => [],
'HttpEnd' => [],
'LogLevel' => [],
'LogWrite' => [],
'UserLogin'=>['app\listener\UserLogin']
],
//事件监听类的写法
<?php
namespace app\listener;
class UserLogin
{
public function handle($user)
{
echo 'UserLogin';
}
}2、通过触发器,进行事件调用
<?php
namespace app\controller;
use app\BaseController;
class Index extends BaseController
{
public function index()
{
event('UserLogin');//等同Event::trigger('UserLogin');
return '';3、事件订阅 触发应该是同上
//通过命令生成订阅类,默认生成app\subscribe\User类
php think make:subscribe User
//监听事件的方法命名规范是on+事件标识
<?php
namespace app\subscribe;
class User
{
public function onUserLogin($user)
{
// UserLogin事件响应处理
}
public function onUserLogout($user)
{
// UserLogout事件响应处理
}
}然后在事件定义文件注册事件订阅者
return [ 'bind' => [ 'UserLogin' => 'app\event\UserLogin', // 更多事件绑定 ], 'listen' => [ 'UserLogin' => ['app\listener\UserLogin'], // 更多事件监听 ], 'subscribe' => [ 'app\subscribe\User', // 更多事件订阅 ],];
