Home > Back-end >  How should I organize my file structure in CodeIgniter4 to save memory?
How should I organize my file structure in CodeIgniter4 to save memory?

Time:11-24

In my CodeIgniter4 codebase, I currently have a handful of files that I have set up as Libraries that include functions that perform wide-ranging purposes and are generally related to specific tables in my database. The functionality of these libraries include:

  • Data analysis and formatting (e.g. pull data from multiple Models, perform some computation, and format it so it can be displayed in Views)
  • Content storage and filtering (e.g. determines the messaging that should be displayed based on the entity's data)
  • Form submission computation (it can be a lot, and didn't want to overload the Controllers)

These Libraries are accessed from multiple Controllers and even some other Libraries. The issue is that I don't know if they should be Libaries or if they should be set up as something else. I don't need new instances of the Libaries each time they are accessed, since that could be a waste of memory. Ideally, they would be set up as Models and accessed through Factories which would share the instance, but these files don't directly manage the data from the application.

Any suggestions?

CodePudding user response:

You can still set those files up a Libraries, but then create a Service so that when you access Share Instances of the Library.

Here is how the Service function would look:

public static function exampleService($getShared = true)
{
    if ($getShared) {
        return static::getSharedInstance('exampleService');
    }

    return new ExampleLibrary();
}

And then this is the constructor of the Controller (or other Library) that is accessing the Library:

public function __construct()
{
    $this->example = service('exampleService');
}
  • Related