米粒人生 2018-12-28 09:59:06 4020次浏览 1条评论 5 5 0

应用举例

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 功能的改进

原文链接:https://blog.csdn.net/qq_24127857/article/details/85317458

觉得很赞
您需要登录后才可以评论。登录 | 立即注册