当前位置: 移动技术网 > IT编程>软件设计>设计模式 > Yii2设计模式——静态工厂模式

Yii2设计模式——静态工厂模式

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

应用举例

yii\db\activerecord

//获取 connection 实例
public static function getdb()
{
    return yii::$app->getdb();
}

//获取 activequery 实例 
public static function find()
{
    return yii::createobject(activequery::classname(), [get_called_class()]);
}

这里用到了静态工厂模式。

静态工厂

利用静态方法定义一个简单工厂,这是很常见的技巧,常被称为静态工厂(static factory)。静态工厂是 new 关键词实例化的另一种替代,也更像是一种编程习惯而非一种设计模式。和简单工厂相比,静态工厂通过一个静态方法去实例化对象。为何使用静态方法?因为不需要创建工厂实例就可以直接获取对象。

和java不同,php的静态方法可以被子类继承。当子类静态方法不存在,直接调用父类的静态方法。不管是静态方法还是静态成员变量,都是针对的类而不是对象。因此,静态方法是共用的,静态成员变量是共享的。

代码实现

//静态工厂
class staticfactory
{
    //静态方法
    public static function factory(string $type): formatterinterface
    {
        if ($type == 'number') {
            return new formatnumber();
        }

        if ($type == 'string') {
            return new formatstring();
        }

        throw new \invalidargumentexception('unknown format given');
    }
}

//formatstring类
class formatstring implements formatterinterface
{
}

//formatnumber类
class formatnumber implements formatterinterface
{
}

interface formatterinterface
{
}

使用:

//获取formatnumber对象
staticfactory::factory('number');

//获取formatstring对象
staticfactory::factory('string');

//获取不存在的对象
staticfactory::factory('object');

yii2中的静态工厂

yii2 使用静态工厂的地方非常非常多,比简单工厂还要多。关于静态工厂的使用,我们可以再举一例。

我们可通过重载静态方法 activerecord::find() 实现对where查询条件的封装:

//默认筛选已经审核通过的记录
public function checked($status = 1)
{
    return $this->where(['check_status' => $status]);
}

和where的链式操作:

student::find()->checked()->where(...)->all();
student::checked(2)->where(...)->all();

详情请参考我的另一篇文章 yii2 scope 功能的改进

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

相关文章:

验证码:
移动技术网