当前位置:网站首页>Laravel服务容器(继承与事件)
Laravel服务容器(继承与事件)
2022-07-29 05:19:00 【廖圣平】
前面写了容器的上下文绑定,接下去看下 继承与事件
在Laravel 框架中,有时需要修改 系统的基础文件,但是修改vender目录下的文件,肯定是不明智的选择,为了框架的扩展性,可以通过容器的继承或事件来修改或者覆盖需要修改的值。
比如我想设置db 的 setDefaultConnection
方法可以这样
$this->app->resolving('setDefaultConnection',function ($db,$app){
$db->setDefaultConnection('ConnectionName');
});
回到 比较实际的例子, 在控制器初始化一个数据
<?php
namespace App\Http\Controllers;
class Nut
{
public $express;
public $data;
public function __construct(\App\Contracts\Express $express)
{
$this->express = $express;
}
public function get()
{
return $this->data;
}
}
我们在原来的基础上新加了一个 data 属性,并输出。
在服务提供者就可以对 这个data 进行初始化了
容器事件
$this->app->resolving('setDefaultConnection',function ($db,$app){
$db->setDefaultConnection('ConnectionName');
});
容器继承
继承的方式和 事件有点像,但是需要返回对象
$this->app->extend('App\Http\Controllers\Nut', function ($service, $app) {
$service->data = 'hello extend';
return $service;
});
git add .
git commit -m 容器的继承与事件
git push
边栏推荐
猜你喜欢
HCIA-R&S自用笔记(26)PPP
微信小程序-屏幕高度
Playwright实战案例之爬取js加密数据
Qtcreator+cmake compiler settings
QT setting background image method
[C language series] - string + partial escape character explanation + annotation tips
DAY15(DAY16拓展):文件包含漏洞
Clickhouse learning (VII) table query optimization
Win10 compiles ffmpeg (including ffplay)
[typescript] in depth study of typescript functions
随机推荐
Day14: upload labs customs clearance tutorial
相对定位和绝对定位
Win10 搭建MSYS2环境
What is sqlmap and how to use it
Day 3
Similarities and differences between REM and PX and EM
Installation steps and environment configuration of vs Code
Relationship between link and @import
Detailed installation and use tutorial of MySQL (nanny installation with pictures and texts)
Cmu15-213 shell lab experiment record
nmap是什么以及使用教程
Clickhouse learning (XI) clickhouseapi operation
QT setting background image method
DAY6:利用 PHP 编写文件上传页面
[C language series] - three methods to simulate the implementation of strlen library functions
Provincial and urban three-level linkage (simple and perfect)
Record the SQL injection vulnerability of XX company
Summary of knowledge points related to forms and forms
·Let's introduce ourselves to the way of programming·
Seay source code audit system