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


    应用举例

    yiidbActiveRecord

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

  • 相关阅读:
    读《人人都是产品经理》
    前端值得看的博客
    git 常用命令 创建查看删除分支,创建查看删除tag等
    看《如何令选择变得更加容易》
    读【失控】——众愚成智
    html5 postMessage
    下拉滚动加载更多数据
    html select用法总结
    分布式系统事务一致性解决方案
    nginx简易教程
  • 原文地址:https://www.cnblogs.com/minirice/p/10188816.html
Copyright © 2020-2023  润新知