开发者

Should I use CONSTANT's of method calls with a Registry pattern in PHP?

On my site I have a config file which has many settings that need to be accessed in many pages, including inside many class files. The config file is included into the header of every page build. Since I will be using a registry method to store some objects in, I am wondering if it would be better for me to store some setting in this 开发者_如何学Pythonclass ass well since it will be available to all my other objects? From my experience over the last couple days, it seems accessing CONSTANTS inside of my class files is difficult sometimes. I am just not sure if it would be a good idea as it would need to call several methods to set and get the settings. Is it common practice to store settings in a registry type object? I have seen on some large projects that they have the methods in place to set/get settings but I have never really seen it in action.


I avoid constants in PHP, they make untestable. This is the gist of my preferred solution:

whatever.ini:

<?php

return array(
  'setting-1' => 'value',
  'setting-2' => 'another value',
);

config.php:

class config
{
  public function __construct($path)
  {
    $this->cfg = include $path;
  }
  private $cfg;
  public function get($key, $default)
  {
    return array_key_exists($this->cfg, $key)
      ? $this->cfg[$key]
      : $default
    ;
  }
}

index.php:

$cfg = new config('my.ini');

...


I like to keep things like this in a registry of some sort. Although for me this is because

  1. the majority of my configuration values are actually multiple parts (ie arrays) so to map much of this out using constants would get pretty long winded. Additionally i dont use php for my config files i always use XML or YAML which is then parsed any way so it jsut makes more sense to go ahead and stick them in a registry as opposed to using constant or globals.
  2. It allows for a single api to get these type of values whther its a db connection object or the path to the webroot on the filesystem

With that said i think it really depends on what the values are and how you intend to use them and if they are structure or essentially flat.


I use a combination of two approaches:

1: In every class/controller, I always start with a require_once('app_config.php') in which I have code like:

define('APP_SMTP_SERVER', 'mail.company.com');

that I can then reference as a constant.

2: I have a singleton "Registry" class where I can store keys and values. It has two exposed methods, getAttribute($key) and setAttribute($key, $value). When I save it to the database, I serialize the value, so it can store any data type you throw at it (single values or arrays, etc.).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜