首先看Engine::Init方法
public function init() {
static $initialized = false;
$self = $this;
if ($initialized) {
// Flight 允許你保存變量,這樣就可以在你的應(yīng)用程序任何地方使用
$this->vars = array();
$this->loader->reset();
$this->dispatcher->reset();
}
// 默認(rèn)的request,response,router,view四個組件
$this->loader->register('request', '\flight\net\Request');
$this->loader->register('response', '\flight\net\Response');
$this->loader->register('router', '\flight\net\Router');
$this->loader->register('view', '\flight\template\View', array(), function($view) use ($self) {
$view->path = $self->get('flight.views.path');
});
//默認(rèn)的框架的方法
$methods = array(
'start','stop','route','halt','error','notFound',
'render','redirect','etag','lastModified','json','jsonp'
);
foreach ($methods as $name) {
//實(shí)際的方法加了_隱藏
$this->dispatcher->set($name, array($this, '_'.$name));
}
// 默認(rèn)的框架配置,也是通過vars存儲的
$this->set('flight.base_url', null);
$this->set('flight.handle_errors', true);
$this->set('flight.log_errors', false);
$this->set('flight.views.path', './views');
$initialized = true;
},
可以看出engine除了核心方法,其他都是通過注冊自定義和擴(kuò)展的。
map($name, $callback) // 創(chuàng)建一個自定義框架的方法。
register($name, $class, [$params], [$callback]) // 注冊一個類的框架方法。
before($name, $callback) // 在一個框架方法之前添加一個過濾器。
after($name, $callback) // 在一個框架方法之后添加一個過濾器。
path($path) // 添加了一個半自動的類路徑。
get($key) // 得到一個變量。
set($key, $value) // 設(shè)置一個變量。
has($key) // 檢查一個變量是否設(shè)置。
clear([$key]) // 清除一個變量。
擴(kuò)展方法通過魔術(shù)方法__call來調(diào)用
public function __call($name, $params) {
$callback = $this->dispatcher->get($name);
//如果是函數(shù)
if (is_callable($callback)) {
return $this->dispatcher->run($name, $params);
}
//否則是類的實(shí)例
$shared = (!empty($params)) ? (bool)$params[0] : true;
return $this->loader->load($name, $shared);
}
通過Loader生成類的實(shí)例,實(shí)例分兩類:單例(共享的)和多例(非共享的)。
public function load($name, $shared = true) {
$obj = null;
if (isset($this->classes[$name])) {
list($class, $params, $callback) = $this->classes[$name];
$exists = isset($this->instances[$name]);
// 判斷是否生成單例對象
if ($shared) {
$obj = ($exists) ?
$this->getInstance($name) :
$this->newInstance($class, $params);
if (!$exists) {
$this->instances[$name] = $obj;
}
}
else {
$obj = $this->newInstance($class, $params);
}
//對于new的對象需要調(diào)用回調(diào)函數(shù)
if ($callback && (!$shared || !$exists)) {
$ref = array(&$obj);
call_user_func_array($callback, $ref);
}
}
return $obj;
}
posted on 2015-04-25 11:14
merlinfang 閱讀(389)
評論(0) 編輯 收藏 引用 所屬分類:
flight