|
|
|
| Как упростить фабрику объектов
<?php
function &load_class($class)
{
static $objects = array();
if( isset($objects[$class]) )
{
return $objects[$class];
}
else
{
if( file_exists($class.'.php') )
{
require_once $class.'.php';
$objects[$class] = new $class();
return $objects[$class];
}
else if( class_exists($class) )
{
$objects[$class] = new $class();
return $objects[$class];
}
}
}
function &get_root()
{
return root::get_root();
}
class root
{
private static $inst;
public function __construct()
{
self::$inst = $this;
}
public static function &get_root()
{
return self::$inst;
}
}
class LoaderClass
{
public function library($library = '', $params = NULL)
{
if( $library == '' )
{
return null;
}
if( ! is_null($params) AND ! is_array($params) )
{
$params = NULL;
}
if( file_exists($library.'.php') )
{
require_once($library . '.php');
$_obj =& get_root();
$lib_name = strtolower($library);
if( (NULL !== $params) )
{
$_obj->$lib_name = new $library( $params );
}
else
{
$_obj->$lib_name = new $library();
}
}
}
}
class CORE extends root{
public function __construct()
{
parent::__construct();
$this->loaderclass =& load_class('LoaderClass');
$this->loaderclass->library('test');
echo $this->test->class_test() . '<br />';
}
}
$core = new CORE();
?>
|
| |
|
|
|
|
|
|
|
для: Ghost
(03.08.2009 в 14:02)
| | не кто так не делает? | |
|
|
|
|
|
|
|
для: Ghost
(13.10.2009 в 10:43)
| |
<?
class Factory {
protected static $loaded = array();
public static function make($library, $params = null) {
if ( !is_array($params) ) $params = null;
if ( self::load($library) ) {
$library = strtolower($library);
return new $library($params);
} else {
throw new Exception('Объект класса '.htmlspecialchars($library).' не может быть создан.');
}
}
protected static function load($library) {
$path = $library.'.php';
if ( in_array($library, self::$loaded) ) return true;
if ( !in_array($library, self::$loaded) && file_exists($path) ) {
include_once($path);
self::$loaded[] = $library;
} else {
return false;
}
}
}
$some_obj = Factory::make('SomeClass', array('param1' => 12, 'param2' => 21));
|
| |
|
|
|