感谢它/wp-dich

此软件包最新版本(dev-master)没有可用的许可信息。

dev-master 2022-02-03 22:46 UTC

This package is auto-updated.

Last update: 2024-08-29 05:12:58 UTC


README

WP_DICH提供了一种使用依赖注入容器智能地处理WordPress钩子的方法,允许懒加载,只有当需要时才加载类。

挑战

假设您只想在特定的WordPress钩子运行时调用一个名为method_a()的方法,来自一个名为Any_Class的类。您会如何做?我想至少有三种方法。

  1. 👎 对象方法调用

这里的问题是您在不需要的情况下初始化了Any_Class(),因为您只需要在wp_footer钩子上调用方法。

class Any_Class{
	public function method_a(){}
}
$any_class = new Any_Class();
add_action( 'wp_footer', array( $any_class, 'method_a') );
  1. 👎 使用匿名函数

这里的缺点是您无法使用remove_action()来移除操作。

class Any_Class{
	public function method_a(){}
}
add_action( 'wp_footer', function(){
	$any_class = new Any_Class();
	$any_class->method_a();
});
  1. 👎 使用静态方法

使用静态方法方法,您的类至少在正确的时间加载,但从设计角度来看,通常最好是坚持使用非静态方法。您不能覆盖它们,它们更难测试,并且您最终不得不围绕它们设计其他需要静态设计的东西。

class Any_Class{
	public static function method_a(){}
}
add_action( 'wp_footer', array('Any_Class', 'method_a') );

👌 WP_DICH解决方案

WP_DICH结合了对象方法调用的优势,使用非静态方法,以及仅在需要时加载类的优势。看看它是多么简单

首先,您需要将依赖注入容器接口传递给WP_DICH()

$dic  = new \Thanks_To_IT\WP_DICH\DIC();
$dich = new \Thanks_To_IT\WP_DICH\WP_DICH( $dic );

WP_DICH已经提供了一个小的依赖注入容器,感谢Carl Alexander,但您可以使用任何库,例如thephpleague/containerphp-di。您只需实现一个带有两个方法的Psr\Container\ContainerInterface,即get()has()

然后,您只需按照您喜欢的设置容器

$dic['any_class_alias'] = function () {
	return new Any_Class();
};

现在,如果您使用在容器上配置的类别名创建钩子,作为数组的第一参数,而不是调用静态方法,它将仅在运行wp_footer钩子时加载您的类,然后调用method_a

$dich->add_action( 'wp_footer', array( 'any_class_alias', 'method_a') );

WP_DICH钩子

您可以使用您熟悉的WordPress钩子函数,如

  • $dich->add_action
  • $dich->add_filter
  • $dich->remove_action
  • $dich->remove_filter

服务

因为我们使用依赖注入容器库,我们可以从一些有趣的功能中受益,如服务,允许只实例化一次类。是的,不再需要考虑单例了。

$dic['any_class_alias'] = $dic->service( function () {
	return new Any_Class();
} );

现在,每次您调用'any_class_alias'时,都会返回相同的对象,而不是每次都创建一个新的对象。

安装

使用Composerthanks-to-it/wp-dich添加到项目的composer.json配置文件的require-dev或require部分,然后运行'composer install'。

{
    "require": {
        "thanks-to-it/wp-dich":"dev-master"
    }
}