配置与设计模式

1.PHP中使用ArrayAccess实现配置文件的加载

$config = new \IMooc\Config(__DIR__.'/configs');
var_dump($config['controller']);

<?php
namespace IMooc;

class Config implements \ArrayAccess
{
protected $path;
protected $configs = array();

function __construct($path)
{
$this->path = $path;
}

public function offsetExists($key)
{
return isset($this->configs[$key]);
}

public function offsetGet($key)
{
if (empty($this->configs[$key]))
{
$file_path = $this->path.'/'.$key.'.php';
$config = require $file_path;
$this->configs[$key] = $config;
return $this->configs[$key];
}
}

public function offsetSet($Key, $value)
{
throw new \Exception("cannot write config file.");
}

public function offsetUnset($key)
{
unset($this->configs[$key]);
}
}

<?php
namespace Configs;
$config = array(
'home' => array(
'decorator' => array(
'IMooc\Decorator\Template',
),
),
'default' => 'hello world',
);
return $config;


2.在工厂方法中读取配置,生成可配置化的对象

$db = \IMooc\Factory::getDatabase();

<?php

namespace IMooc;

class Factory
{

static function getDatabase($id = 'master')
{
$key = 'database_'.$id;

if ($id == 'slave')

{

$slaves = Application::getInstance()->config['database']['slave'];

$db_conf = $slaves[array_rand($slaves)];

}

else

{

$db_conf = Application::getInstance()->config['database']
[$id];

}

$db = Register::get($key);

if (!$db)

{
$db = new Database\MySQLi();

$db->connect($db_conf['host'], $db_conf['user'], $db_conf['password'], $db_conf['dbname']);

Register::set($key, $db);

}

return $db;
}
}


3.使用装饰器模式实现权限验证,模板渲染,JSON串化
4.使用观察者模式实现数据更新事件的一系列更新操作
5.使用代理模式实现数据的主从自动切换


来自为知笔记(Wiz)


posted on 2016-12-24 22:14  果然朝辉  阅读(474)  评论(0编辑  收藏  举报

导航