(Lys) Factory

Mardi 01 Avril 2025, 11:11:58

<?php
/**
* Lys
*
* GNU General Public License
*
* Copyright © 2007 - 2023, Yohann Schwan. All rights reserved.
*/
namespace Lys {

class
Factory
{
/**
* @var array
*/
private static $attributes = array();

/**
* @var array
*/
private static $instances = array();

/**
* @args string $name
* @return object
*/
static function attributes()
{
return
self::$attributes;
}


/**
* @args string $name
* @return object
*/
static function exists($name)
{
return isset(
self::$attributes[$name]);
}

/**
* @args string $name
* @return object
*/
static function get($name)
{
if(isset(
self::$instances[$name]))
{
return
self::$instances[$name];
}

if(isset(
self::$attributes[$name]))
{
list(
$c, $d, $v) = self::$attributes[$name];

foreach(
$d as $dk => $dv)
{
$d[$dk] = self::get($dv);
}

self::$instances[$name] = new $c($d + $v);

return
self::$instances[$name];
}

throw new
LogicException('(Lys\\Factory) Undefined object');
}

/**
* @args string $name, string $class, array $dependencies = array(), array $values = array()
* @return void
*/
static function set($name, $class, array $dependencies = array(), array $values = array())
{
if(isset(
self::$instances[$name]))
{
throw new
LogicException('(Lys\\Factory) Unable to redefine object');
}

if(isset(
self::$attributes[$name]))
{
throw new
LogicException('(Lys\\Factory) Unable to redefine attributes');
}

self::$attributes[$name] = array($class, $dependencies, $values);
}
}
}