zoukankan      html  css  js  c++  java
  • 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 功能的改进

  • 相关阅读:
    Win7专业版系统下事件绑定的Command事件不执行
    Win8系统下报错:无法将字符串“*”转换为Length.
    C#创建job计划用于调用存储过程刷新数据
    with语句
    for in语句与for in语句输入顺序问题
    HighCharts日期及数值格式化
    在web.config文件中,增加“type="APP.Modules.CommandModule,CommandModules"”节点会导致awesome font字体图标显示为方框框
    String、StringBuffer与StringBuilder之间区别
    java使用maven创建springmvc web项目
    手机APP下单支付序列图
  • 原文地址:https://www.cnblogs.com/echojson/p/10789567.html
Copyright © 2011-2022 走看看