当前位置: 移动技术网 > IT编程>开发语言>PHP > Laravel中简约却不简单的Macroable宏指令详解

Laravel中简约却不简单的Macroable宏指令详解

2018年08月08日  | 移动技术网IT编程  | 我要评论

百度百科的定义:

计算机科学里的宏(macro),是一种批量处理的称谓。一般说来,宏是一种规则或模式,或称语法替换 ,用于说明某一特定输入(通常是字符串)如何根据预定义的规则转换成对应的输出(通常也是字符串)。这种替换在预编译时进行,称作宏展开。

我一开始接触宏是在大学上计算机基础课程时,老师讲office时说的。那时老师介绍宏操作时没太在意,只记得这一操作很强大,它能使日常工作变得更容易。

今天我们讲讲laravel中的宏操作

首先完整的源码

<?php
 
namespace illuminate\support\traits;
 
use closure;
use reflectionclass;
use reflectionmethod;
use badmethodcallexception;
 
trait macroable
{
 /**
 * the registered string macros.
 *
 * @var array
 */
 protected static $macros = [];
 
 /**
 * register a custom macro.
 *
 * @param string $name
 * @param object|callable $macro
 *
 * @return void
 */
 public static function macro($name, $macro)
 {
 static::$macros[$name] = $macro;
 }
 
 /**
 * mix another object into the class.
 *
 * @param object $mixin
 * @return void
 */
 public static function mixin($mixin)
 {
 $methods = (new reflectionclass($mixin))->getmethods(
  reflectionmethod::is_public | reflectionmethod::is_protected
 );
 
 foreach ($methods as $method) {
  $method->setaccessible(true);
 
  static::macro($method->name, $method->invoke($mixin));
 }
 }
 
 /**
 * checks if macro is registered.
 *
 * @param string $name
 * @return bool
 */
 public static function hasmacro($name)
 {
 return isset(static::$macros[$name]);
 }
 
 /**
 * dynamically handle calls to the class.
 *
 * @param string $method
 * @param array $parameters
 * @return mixed
 *
 * @throws \badmethodcallexception
 */
 public static function __callstatic($method, $parameters)
 {
 if (! static::hasmacro($method)) {
  throw new badmethodcallexception("method {$method} does not exist.");
 }
 
 if (static::$macros[$method] instanceof closure) {
  return call_user_func_array(closure::bind(static::$macros[$method], null, static::class), $parameters);
 }
 
 return call_user_func_array(static::$macros[$method], $parameters);
 }
 
 /**
 * dynamically handle calls to the class.
 *
 * @param string $method
 * @param array $parameters
 * @return mixed
 *
 * @throws \badmethodcallexception
 */
 public function __call($method, $parameters)
 {
 if (! static::hasmacro($method)) {
  throw new badmethodcallexception("method {$method} does not exist.");
 }
 
 $macro = static::$macros[$method];
 
 if ($macro instanceof closure) {
  return call_user_func_array($macro->bindto($this, static::class), $parameters);
 }
 
 return call_user_func_array($macro, $parameters);
 }
}

macroable::macro方法

public static function macro($name, $macro)
{
 static::$macros[$name] = $macro;
}

很简单的代码,根据参数的注释,$macro可以传一个闭包或者对象,之所以可以传对象,多亏了php中的魔术方法

class father
{
 // 通过增加魔术方法**__invoke**我们就可以把对象当做闭包来使用了。
 public function __invoke()
 {
 echo __class__;
 }
}
 
class child
{
 use \illuminate\support\traits\macroable;
}
 
// 增加了宏指令之后,我们就能调用 child 对象中不存在的方法了
child::macro('show', new father);
// 输出:father
(new child)->show();

macroable::mixin方法

这个方法是把一个对象的方法的返回结果注入到原对象中

public static function mixin($mixin)
{
 // 通过反射获取该对象中所有公开和受保护的方法
 $methods = (new reflectionclass($mixin))->getmethods(
  reflectionmethod::is_public | reflectionmethod::is_protected
 );
 
 foreach ($methods as $method) {
  // 设置方法可访问,因为受保护的不能在外部调用
  $method->setaccessible(true);
 
  // 调用 macro 方法批量创建宏指令
  static::macro($method->name, $method->invoke($mixin));
 }
}
 
// 实际使用
class father
{
 public function say()
 {
  return function () {
   echo 'say';
  };
 }
 
 public function show()
 {
  return function () {
   echo 'show';
  };
 }
 
 protected function eat()
 {
  return function () {
   echo 'eat';
  };
 }
}
 
class child
{
 use \illuminate\support\traits\macroable;
}
 
// 批量绑定宏指令
child::mixin(new father);
 
$child = new child;
// 输出:say
$child->say();
// 输出:show
$child->show();
// 输出:eat
$child->eat();

在上面的代码可以看出mixin可以将一个类的方法绑定到宏类中。需要注意的就是,方法必须是返回一个闭包类型。

* macroable::hasmacro方法

public static function hasmacro($name)
{
 return isset(static::$macros[$name]);
}

这个方法就比较简单没什么复杂可言,就判断是否存在宏指令。通常是使用宏指令之前判断一下。

* macroable::__call和macroable::__callstatic方法

正是由于这两个方法,我们才能进行宏操作,两个方法除了执行方式不同,代码大同小异。这里讲一下__call

public function __call($method, $parameters)
{
 // 如果不存在这个宏指令,直接抛出异常
 if (! static::hasmacro($method)) {
  throw new badmethodcallexception("method {$method} does not exist.");
 }
 
 // 得到存储的宏指令
 $macro = static::$macros[$method];
 
 // 闭包做一点点特殊的处理
 if ($macro instanceof closure) {
  return call_user_func_array($macro->bindto($this, static::class), $parameters);
 }
 
 // 不是闭包,比如对象的时候,直接通过这种方法运行,但是要确保对象有`__invoke`方法
 return call_user_func_array($macro, $parameters);
}
 
 
class child
{
 use \illuminate\support\traits\macroable;
 
 protected $name = 'father';
}
 
// 闭包的特殊处理,需要做的就是绑定 $this, 如
child::macro('show', function () {
 echo $this->name;
});
 
// 输出:father
(new child)->show();

在上面的操作中我们绑定宏时,在闭包中可以通过$this来调用child的属性,是因为在__call方法中我们使用closure::bindto方法。

官网对closure::bindto的解释:复制当前闭包对象,绑定指定的$this对象和类作用域。

laravel 中对类增加宏指令

laravel中很多类都使用了宏这个trait

比如illuminate\filesystem\filesystem::class,我们想为这个类增加一个方法,但不会动到里面的代码。

1. 我们只需要到app\providers\appserviceprovider::register方法增加宏指令(你也可以专门新建一个服务提供者专门处理)


2. 然后增加一条测试路由,测试我们新增加的方法

3. 然后打开浏览器运行,你就会发现,我们的代码可以正常的运行了并输出结果了

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网