zoukankan      html  css  js  c++  java
  • 配置与设计模式

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

    $config = new IMoocConfig(__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(
    'IMoocDecoratorTemplate',
    ),
    ),
    'default' => 'hello world',
    );
    return $config;


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

    $db = IMoocFactory::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 DatabaseMySQLi();

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

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

    }

    return $db;
    }
    }


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




  • 相关阅读:
    云计算设计模式(三)——补偿交易模式
    云计算设计模式(二)——断路器模式
    Java Web开发之详解JSP
    Java Web开发之Servlet、JSP基础
    Android数据库开发——SQLite
    Android控件开发——ListView
    Android服务开发——WebService
    Android开发学习路线图
    Android项目的目录结构
    Windows下搭建Android开发环境
  • 原文地址:https://www.cnblogs.com/phonecom/p/95374b19272382d44abf22d5c0c2fb45.html
Copyright © 2011-2022 走看看