我想要一个小的 php 模块。该模块将具有纯函数的方法。所以,这只是函数的集合。所有函数都会获取一些参数并仅根据输入参数返回结果。
我有一些建议:
<强>1。静态类
PHP 没有真正的静态类,所以我只是创建一个包含所有静态方法的类:
class Some_Module
{
static public function sum($a, $b, $c)
{
return $a+$b+$c;
}
static public function method2($a, $b)
{
return $a-$b+5;
}
}
使用此类模块非常容易:
$x = Some_module::sum(1,2,3);
但是,我听说(有很多关于 SO 的主题),静态是一种不好的做法。
<强>2。单例
使用起来并不容易:
// we should not to forget to get instance
$module_instance = new Some_module;
$x = $module_instance->sum(1,2,3);
不方便的是,我们现在应该初始化这个模块。 另外,有大量关于 SO 的主题,其中解释了为什么 Singleton 在 PHP 中没有用,所以这也是一个不好的做法。
这样的模块使用什么模式?
最佳答案
我认为这次讨论将有助于您的决定Static methods: are they still bad considering PHP 5.3 late static binding?
就个人而言,这取决于上下文。存储一堆杂项。辅助方法,我更有可能将其用作全局和命名空间。在存储不需要实例化的特定类别的有限数量的方法时,静态类可能是一个不错的选择。只是要注意,出于单元测试的目的,许多类在错误的上下文中使用静态方法,例如 cool::method
将会是 hell 。
// keep it abstract to prevent it from being instantiated
abstract class Foo {
// cannot be altered if inherited, although limitation still exists
final public static function bar() {
echo 'test';
}
}
Foo::bar();
关于php - php 模块选择什么模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9106482/