CI自定义适配器最佳实践
本帖最后由 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
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
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
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);
}
}
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();
那这段呢?可以直接调用自己的子类吗?怎么实现这个呀 适配器的价值在哪里?有什么用呢 适配器模式使得一个类可以同时使用两个基础类的功能,跳出了单纯继承的限制。有效的重用多各类。 通过config指定要调用的实现?
页:
[1]