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

应用举例

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 关键词实例化的另外一种替代,也更像是一种编程习惯而非一种设计模式。和简单工厂相比,静态工厂经过一个静态方法去实例化对象。为什么使用静态方法?由于不须要建立工厂实例就能够直接获取对象。app

和Java不一样,PHP的静态方法能够被子类继承。当子类静态方法不存在,直接调用父类的静态方法。无论是静态方法仍是静态成员变量,都是针对的类而不是对象。所以,静态方法是共用的,静态成员变量是共享的。yii

代码实现

//静态工厂
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
{
}

使用:this

//获取FormatNumber对象
StaticFactory::factory('number');

//获取FormatString对象
StaticFactory::factory('string');

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

Yii2中的静态工厂

Yii2 使用静态工厂的地方很是很是多,比简单工厂还要多。关于静态工厂的使用,咱们能够再举一例。spa

咱们可经过重载静态方法 ActiveRecord::find() 实现对where查询条件的封装:.net

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

和where的链式操做:设计

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

详情请参考个人另外一篇文章 Yii2 Scope 功能的改进code

相关文章
相关标签/搜索