💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
> ## 依赖注入请求对象(针对控制器) ### 如果继承了系统的Controller类的话,可以直接调用request属性,例如: ``` use think\Controller; class Index extends Controller { public function hello() { return 'Hello,'.$this->request->param('name'); } } ``` ### 注入控制器的构造方法中 ``` use think\Request; class Index { protected $request; // 用来保存请求对象 // 将请求对象注入构造方法 public function __construct(Request $request) { $this->request = $request; } // 在其他方法中使用请求对象 public function hello() { return 'Hello,' . $this->request->param('name') . '!'; } } ``` ### 注入控制器的一般方法中 ``` use think\Request; class Index { public function hello(Request $request) { return 'Hello,' . $request->param('name') . '!'; } } ``` >## 依赖注入任意类的对象(针对控制器) ### 注入控制器的构造方法中 ``` use app\index\model\User; class Index { protected $user; public function __construct(User $user) { $this->user = $user; } } ``` ### 注入控制器的一般方法中 ``` use app\index\model\User; use think\Controller; class Index extends Controller { public function hello(User $user) { return 'Hello,'.$user->name; } } // 事先在Request进行对象绑定 Request::instance()->bind('user', \app\index\model\User::get(1)); // 如果没有事先在Request进行对象绑定,那么当调用hello方法时会自动实例化一个对象,相当于下面 Request::instance()->bind('user', new \app\index\model\User); ``` ### 调用依赖注入类的静态invoke方法可以自动实例化注入的对象 ``` class User extends Model { // 需要传入当前请求对象作为参数 public static function invoke(Request $request) { $id = $request->param('id'); return User::get($id); } } ```