如何使用codeigniter实施工厂模式?

时间:2019-03-22 17:07:35

标签: php codeigniter-3 factory-pattern

我需要实现一个名为“学习技能”的功能。在控制器中,我添加了以下代码:

public function learnskill( $character_id, $skillname )
{
    $this->load->model('skillfactory_model');
    // Ideally i would need that the factory returns the model
    // skill_parry_model so i can use it
    $skill_instance = $this->skill_factory_model->create($skillname);
    $skill_instance->learn($character_id);
 }

如何实现模型“ skill_factory_model”以及如何编写控制器并遵循CI准则?

1 个答案:

答案 0 :(得分:0)

找到一种解决方法:

public function learnskill( $character_id, $skillname )
{  

    $this->load->model('skillfactory_model');
    $model = $this->skillfactory_model->create($skillname]);
    $this->load->model($model);
    $this->$model->learn($character_id);
}

SkillFactory_Model:

class SkillFactory_Model extends CI_Model
{

    public function create($tag)
    {   
        $class = "Skill_" . $tag . '_model';                        
        return $class;
    }

}