内容简介:向容器中注册服务扩展已有服务Manager实际上是一个工厂,它为服务提供了驱动管理功能。
注册服务
向容器中注册服务
// 绑定服务
$container->bind('log', function(){
return new Log();
});
// 绑定单例服务
$container->singleton('log', function(){
return new Log();
});
扩展绑定
扩展已有服务
$container->extend('log', function(Log $log){
return new RedisLog($log);
});
Manager
Manager实际上是一个工厂,它为服务提供了驱动管理功能。
Laravel中的很多组件都使用了Manager,如: Auth
、 Cache
、 Log
、 Notification
、 Queue
、 Redis
等等,每个组件都有一个 xxxManager
的管理器。我们可以通过这个管理器扩展服务。
比如,如果我们想让 Cache
服务支持 RedisCache
驱动,那么我们可以给 Cache
服务扩展一个 redis
驱动:
Cache::extend('redis', function(){
return new RedisCache();
});
这时候, Cache
服务就支持 redis
这个驱动了。现在,找到 config/cache.php
,把 default
选项的值改成 redis
。这时候我们再用 Cache
服务时,就会使用 RedisCache
驱动来使用缓存。
Macro和Mixin
有些情况下,我们需要给一个类动态增加几个方法, Macro
或者 Mixin
很好的解决了这个问题。
在 Laravel 底层,有一个名为 Macroable
的 Trait
,凡是引入了 Macroable
的类,都支持 Macro
和 Mixin
的方式扩展,比如 Request
、 Response
、 SessionGuard
、 View
、 Translator
等等。
Macroable
提供了两个方法, macro
和 mixin
, macro
方法可以给类增加一个方法, mixin
是把一个类中的方法混合到 Macroable
类中。
举个例子,比如我们要给 Request
类增加两个方法。
使用 macro
方法时:
Request::macro('getContentType', function(){
// 函数内的$this会指向Request对象
return $this->headers->get('content-type');
});
Request::macro('hasField', function(){
return !is_null($this->get($name));
});
$contentType = Request::getContentstType();
$hasPassword = Request::hasField('password');
使用 mixin
方法时:
class MixinRequest{
public function getContentType(){
// 方法内必须返回一个函数
return function(){
return $this->headers->get('content-type');
};
}
public function hasField(){
return function($name){
return !is_null($this->get($name));
};
}
}
Request::mixin(new MixinRequest());
$contentType = Request::getContentType();
$hasPassword = Request::hasField('password');
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 【php 扩展开发】扩展生成器
- 喧喧发布 1.6.0 版本,扩展机制增强,支持服务器扩展
- 为vscode编写扩展
- JavaScript——DOM扩展
- Mac内核扩展开发
- VisualStudio 扩展开发
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
PHP Hacks
Jack Herrington D. / O'Reilly Media / 2005-12-19 / USD 29.95
Programmers love its flexibility and speed; designers love its accessibility and convenience. When it comes to creating web sites, the PHP scripting language is truly a red-hot property. In fact, PH......一起来看看 《PHP Hacks》 这本书的介绍吧!