用户
 找回密码
 入住 CI 中国社区
搜索
查看: 3736|回复: 4
收起左侧

[讨论/交流] CI自定义适配器最佳实践

[复制链接]
发表于 2011-6-17 13:47:07 | 显示全部楼层 |阅读模式
本帖最后由 rebill 于 2011-6-17 14:53 编辑

看了手册(http://codeigniter.org.cn/user_guide/general/creating_drivers.html),于是决定自己动手测试一下。

根据手册的描述。我们按以下步骤来测试:

1.创建目录:/application/libraries/Video
2.创建Driver:/application/libraries/Video/Video.php
PHP复制代码
<?php
 
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
 
class Video extends CI_Driver_Library {
 
    protected $valid_drivers = array(
        'video_youku', 'video_tudou'
    );
    protected $_adapter;
 
    public function __construct($config = array()) {
        if (!empty($config)) {
            $this->_initialize($config);
        }
    }
 
    private function _initialize($config) {
        $this->_adapter = $config['adapter'];
    }
 
    public function get($id) {
        return $this->{$this->_adapter}->get($id);
    }
 
    public function __get($child) {
        return parent::__get($child);
    }
 
}
复制代码

3.创建Adater:/application/libraries/Video/dirvers/Video_youku.php
PHP复制代码
<?php
 
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
 
class Video_youku extends CI_Driver {
 
    public function __construct() {
       
    }
 
    public function get($id) {
        return 'Testing' . $id;
    }
 
}
复制代码

4.调用
PHP复制代码
<?php
 
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
 
class Test extends CI_Controller {
 
    public function __construct() {
        parent::__construct();
        $this->load->driver('video', array('adapter' => 'youku'));
    }
 
    public function index() {
        echo $this->video->get(123);
           
    }
}
 
复制代码


评分

参与人数 1威望 +5 收起 理由
lamtin + 5 赞一个!

查看全部评分

发表于 2011-7-2 18:08:38 | 显示全部楼层
The child classes, the drivers themselves, can then be called directly through the parent class, without initializing them:

$this->some_parent->child_one->some_method();
$this->some_parent->child_two->another_method();
那这段呢?可以直接调用自己的子类吗?怎么实现这个呀
发表于 2011-7-13 00:33:06 | 显示全部楼层
适配器的价值在哪里?有什么用呢
发表于 2011-7-22 11:50:39 | 显示全部楼层
适配器模式使得一个类可以同时使用两个基础类的功能,跳出了单纯继承的限制。有效的重用多各类。
发表于 2011-7-22 15:11:40 | 显示全部楼层
通过config指定要调用的实现?

本版积分规则