<?php
class Services
{
protected $services = [];
public function get($id, callable $creator)
{
// Нет в кэше? Берём из creator'а
if (! isset($this->services[$id]))
$this->services[$id] = $creator();
// Возвращаем кэш
return $this->services[$id];
}
public function set($id, $service)
{
$this->services[$id] = $service;
}
}
class Framework
{
protected static $services = null;
public static function getServices()
{
if (is_null(static::$services)) {
throw new \Exception('Не инициализировано');
}
return static::$services;
}
public static function getRouter()
{
return static::getServices()->get('framework.router', function() {
return "router";
});
}
public static function init() // Можно в качестве аргумента передать нужную реализацию Services
{
static::$services = new Services();
}
public static function run()
{
// Маршрутизация => Контроллер => Выполнение Response
}
}
class CMS extends Framework
{
public static function getModulesManager()
{
return static::getServices()->get('cms.modulesmanager', function() {
return "modulesManager";
});
}
public static function run()
{
// Маршрутизация => Встроенные контроллеры/Модули => Выполнение Response
}
}
// based on framework
Framework::init() && Framework::run();
// где-то в компоненте:
var_dump(Framework::getRouter());
// based on CMS
CMS::init() && CMS::run();
// где-то в модуле:
var_dump(CMS::getRouter());
var_dump(CMS::getModulesManager());
CMS::getServices()->set('framework.router', 'Ha, its not router!');
var_dump(CMS::getRouter());
string(6) "router"
string(6) "router"
string(14) "modulesManager"
string(19) "Ha, its not router!"
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
string(6) "router"
string(6) "router"
string(14) "modulesManager"
string(19) "Ha, its not router!"