Welcome Guest, Not a member yet? Register   Sign In
CI 4.4.0 modules shared services not working
#1

Hi guys,
Long story short:
I have multiple modules. Base module has Alert class which collects all system messages while loading through Controller, Models, logic etc.
That is why i need shared instance functionality and Services was perfect for that.
At the controller end, when layout view loads, i want to print all collected messages on a screen.

This approach did work in CodeIgniter 4.3.7 version. Just did upgrade to 4.4.0 and this does not work anymore.

Below is simplified code to catch the idea

App\Config\Modules.php
PHP Code:
class Modules extends BaseModules
{
    public $enabled true;

    public $aliases = [
        'events',
        'filters',
        'registrars',
        'routes',
        'services',
    ];


App\Config\Autoload.php
PHP Code:
class Autoload extends AutoloadConfig
{
    public $psr4 = [
        APP_NAMESPACE => APPPATH// For custom app namespace
        'Config'      => APPPATH 'Config',
        'Modules'    => ROOTPATH 'Modules'// my custom modules
    ];


Modules\Base\Config\Services.php
PHP Code:
use Modules\Base\Libraries\Alert;

class 
Services extends BaseService
{
    public static function Alert(bool $getShared true): Alert
    
{
        if ($getShared) {
            return static::getSharedInstance('Alert') ?? new Alert();
        }

        return new Alert();
    }


Modules\Base\Libraries\Alert.php
PHP Code:
namespace Modules\Base\Libraries;

class 
Alert
{
    public array $messages = [];

    public function set(string $typestring $message): void
    
{
        $this->messages[] = ['type' => $type'message' => $message];
    }

    public function getMessages(): array
    {
        return $this->messages;
    }


Modules\Base\Contollers\BaseController.php
PHP Code:
class BaseController extends Controller
{
    public Alert $alert;

    public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger)
    {
        $this->alert = \Modules\Base\Config\Services::Alert(); // load shared isntance. In real life this is the 1st isntance

        $this->alert->set('danger''This message will show in red!');


        dd(service('alert')); 
    }


response is empty "service(...) null"


Anywhere in frontend layout views i want to display potential system messages and shared instance is null

PHP Code:
dd(service('Alert')->getMessages());
ErrorCall to a member function getMessages() on null 


As far as i understand, Services can load class outside of App\Config\Services scope but can't keep it or recognize as shared instance for multiple use down the code

Am i missing anything? Any ideas? Suggestions?
Reply


Messages In This Thread
CI 4.4.0 modules shared services not working - by davis.lasis - 08-30-2023, 02:39 AM



Theme © iAndrew 2016 - Forum software by © MyBB