module()
public function module(string $target_module): void
Description
Loads a module and makes it available as a property within model files. This method locates the module's controller file, requires it, instantiates the controller class, and caches the instance in the loaded_modules array. Once loaded, the module can be accessed as $this->module_name.
This method is necessary in model files to distinguish between database access (which is automatic) and module usage (which requires explicit loading). After calling $this->module('tax'), you can use $this->tax->calculate() to invoke methods from the Tax module.
The method supports both standard modules and child modules (using parent-child naming conventions with hyphens).
Parameters
| Parameter | Type | Description | Default |
|---|---|---|---|
| $target_module | string | The name of the module to load. For child modules, use the format 'parent-child'. | N/A |
Return Value
| Type | Description |
|---|---|
| void | This function does not return a value. The loaded module becomes available as a property. |
Throws
| Exception | Description |
|---|---|
| Exception | Thrown if the module controller file cannot be found or the controller class does not exist. |
Example Usage
Basic module loading:
<?php
// In a model file
class Orders_model extends Model {
public function process_payment($order_id) {
// Load the payment processor module
$this->module('payment_processor');
// Now use it
$result = $this->payment_processor->charge($order_id);
return $result;
}
}Loading multiple modules:
public function send_order_confirmation($order_id) {
// Load required modules
$this->module('email_sender');
$this->module('pdf_generator');
// Use them
$pdf = $this->pdf_generator->create_invoice($order_id);
$this->email_sender->send_with_attachment($email, $subject, $pdf);
}Module loading is idempotent (safe to call multiple times):
$this->module('tax'); // Loads the module
$this->module('tax'); // Does nothing (already loaded)Notes
- This method is only necessary when using non-database modules in model files
- Database access via
$this->dbor$this->analyticsdoes not require callingmodule() - The method caches loaded modules, so calling it multiple times for the same module is safe and efficient
- In controllers, module loading can be automatic or explicit; in models, it must be explicit