简体   繁体   中英

How can i implement a factory pattern with codeigniter?

I need to implement a function called 'learn skill'. In the controller i added this code:

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);
 }

How can i implement the model 'skill_factory_model' and how i can write the controller and follow CI guidelines?

Found out a way to do it:

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;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM